# Clear environment

rm(list=ls())

library(dplyr)
library(ggplot2)
library(here)
setwd(here())

# Generic SESOI graph

d=data.frame(y="", 
             ATE=-.2, lower=-.5, 
             upper=.1,
             sesoi = -.75)
plot1<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-1.25, xmax=d$sesoi, ymin=0, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(d$sesoi, d$ATE, 0), 
                     labels=c("SESOI",
                              expression(hat(beta)),
                              "0")) +
  geom_vline(xintercept=0, linetype=c("dotted"), color=c("black")) +
  geom_vline(xintercept=d$sesoi, linetype=c("solid"), color=c("black")) +
  theme_classic() + ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=20), 
    axis.ticks.y = element_blank())  +
  coord_cartesian(xlim = c(-1, 0.2))
pdf(file="tabs-figs/sesoi_generic.pdf",
    height=2, width=8)
plot1
dev.off()

library(readstata13)
#load raw survey data (includes the Phase 1 control communities)
dat.hh<-read.dta13("wave4_merged_READY_district.dta")
dat.cl<-read.dta13("wave4_CL_READY_district.dta")
dat.ts<-read.dta13("wave4_TS_READY_new.dta")

#########################################
#  PRE-PROCESSING STEPS FOR EACH SURVEY
#########################################

#### HOUSEHOLD AND CHILD 

# constructing the sampling weights to scale sample to population

vil.sizes<-read.dta13("estimated village sizes 2022-08.dta")
row.names(vil.sizes)<-vil.sizes$vuid
#who is not in the endline?:
dat.hh$num_hh_needsassmnt<-vil.sizes[dat.hh$VUID,]$num_hh_needsassmnt
vil.surveys<-rowSums(table(dat.hh$VUID, dat.hh$HHID)>0)
dat.hh$num_hh_endline_surveyed<-vil.surveys[dat.hh$VUID]
dat.hh$ss_wt<-dat.hh$num_hh_needsassmnt/dat.hh$num_hh_endline_surveyed

# constructing additional outcomes

dat.hh$ros_attend    <-1*((dat.hh$ros_attend_CBE==1)|(dat.hh$ros_attend_govschool==1))
dat.hh$teacher_attend_score <- 1-(dat.hh$q54_r/6)

# eligibility indicator

dat.hh$ros_age0813  <-   (dat.hh$ros_age<14)&(dat.hh$ros_age>7)

# additional measures on parental involvement

# recode q37 about frequency of parents helping kids with homework

dat.hh$q37_recode <- NA  # Initialize a new variable for recoded values

# recode the responses based on the frequencies
dat.hh$q37_recode[dat.hh$q37 == 1] <- 5
dat.hh$q37_recode[dat.hh$q37 == 2] <- 4
dat.hh$q37_recode[dat.hh$q37 == 3] <- 3
dat.hh$q37_recode[dat.hh$q37 == 4] <- 2
dat.hh$q37_recode[dat.hh$q37 == 5] <- 1

# Handle the "Not applicable", "Refused", and "Don't Know" 
# Code "Not applicable" and "Don't know" as 1-never,
# so that interpretation is how often are you aware
# of helping your child with homework.
# Code refused as NA.

dat.hh$q37_recode[dat.hh$q37 == 95] <- 1
dat.hh$q37_recode[dat.hh$q37 == 98] <- NA
dat.hh$q37_recode[dat.hh$q37 == 99] <- 1

# Check the recoded values
table(dat.hh$q37_recode)

# create a new variable that takes a sum of q40a-q40j "yes" responses
dat.hh$q40 <- rowSums(dat.hh[, paste0("q40",c("a","b","c","d","e","f","g","h","i","j"),"_b")])

table(dat.hh$q40)

# design variables

dat.hh$TREAT<-(dat.hh$TCode>0)*1
dat.hh$HAND <-(dat.hh$HAND==1)*1
dat.hh$wt          <-((1-dat.hh$TREAT)/.27+(dat.hh$TREAT)/((1-.27)/2))*dat.hh$ss_wt
t.hhid<-table(dat.hh$HHID, useNA = "always")
uid<-(cbind(c(1:length(dat.hh$HHID)), dat.hh$HHID, dat.hh$CHID))[order(dat.hh$HHID),]
within.hh.id<-cbind(as.numeric(rep(names(t.hhid), times=t.hhid)) 
                    ,as.vector(do.call(c,  sapply(t.hhid, function(nhh) c(1:nhh))))
)
table(as.vector(uid[,2])==as.vector(within.hh.id[,1]))
uid<-cbind(uid, within.hh.id[,2])
table(uid[order(uid[,1]),3]==dat.hh$CHID)
dat.hh$within.hh.id<-uid[order(uid[,1]),4]

#### COMMUNITY LEADER

# merge in variables from the randomization file 
# CLUSTER to get clustering of villages and also variables used in the rerandomization

dat.cl$PROVINCE1<-1*(dat.cl$Province=="Parwan")
dat.cl$PROVINCE2<-1*(dat.cl$Province=="Kapisa")
dat.cl$PROVINCE3<-1*(dat.cl$Province=="Herat")
dat.cl$PROVINCE4<-1*(dat.cl$Province=="Bamian")
dat.cl$PROVINCE5<-1*(dat.cl$Province=="Ghur")
dat.cl$PROVINCE6<-1*(dat.cl$Province=="Dykundi")
if(max(dat.cl$cl_barriers_security_score, na.rm=TRUE)>1){
  dat.cl$q10_r<-(dat.cl$q10_r-1)/2
  dat.cl$q12_r<-(dat.cl$q12_r-1)/2
  dat.cl$cl_barriers_security_score<-(dat.cl$q8c_r+dat.cl$q9_r+dat.cl$q10_r+dat.cl$q11_r+dat.cl$q12_r)/5
}
if(max(dat.cl$cl_community_activity_score, na.rm=TRUE)>1){
  dat.cl$q38_r[dat.cl$q38_r>25]<-25
  dat.cl$q38_r[dat.cl$q38_r>25]<-25
  dat.cl$q38_r<-dat.cl$q38_r/25
  dat.cl$cl_community_activity_score<-rowSums(dat.cl[,c("q35a_b", "q35b_b", "q35c_b", "q38_r", 
                                                        "q41a_r", "q41b_r", "q41c_r", "q41d_r", 
                                                        "q48a_r", "q48b_r", "q48c_r", "q48d_r", 
                                                        "q48e_r", "q48f_r", "q48i_r", "q48j_r")])/16
}

# assign village size variable to dat

dat.cl$num_hh_needsassmnt<-vil.sizes[dat.cl$VUID,]$num_hh_needsassmnt
dat.cl$ss_wt<-1
dat.cl$wt<-1

# design variables
dat.cl$TREAT<-(dat.cl$TCode>0)*1
dat.cl$HAND <-(dat.cl$HAND==1)*1

# processing existing outcomes 

dat.cl$sustain.index<-round(dat.cl$phone_sustain_initiative_score*3+dat.cl$phone_sustain_provisions_score*8+
                              dat.cl$phone_sustain_confidence_score+dat.cl$phone_sustain_2018_score, 4)
table(dat.cl$sustain.index)

dat.cl$phone_community_engagement_score_std<-(dat.cl$phone_community_engagement_score
                                           -mean(dat.cl$phone_community_engagement_score[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE)
)/sd(dat.cl$phone_community_engagement_score[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE) 

dat.cl$phone_sustain_initiative_score_std<-(dat.cl$phone_sustain_initiative_score
                                         -mean(dat.cl$phone_sustain_initiative_score[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE)
)/sd(dat.cl$phone_sustain_initiative_score[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE) 

dat.cl$phone_sustain_provisions_score_std<-(dat.cl$phone_sustain_provisions_score
                                         -mean(dat.cl$phone_sustain_provisions_score[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE)
)/sd(dat.cl$phone_sustain_provisions_score[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE) 

dat.cl$sustain.index_std<-(dat.cl$sustain.index
                        -mean(dat.cl$sustain.index[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE)
)/sd(dat.cl$sustain.index[dat.cl$TREAT==1&dat.cl$HAND==0], na.rm=TRUE) 

# Community desire to continue is 0 in the raw data:

dat.cl$phone_sustain_want_score_rev <- 1-dat.cl$phone_sustain_want_score

#to create new indexes
index.inflate<-function(x){
  tmp<-as.numeric(names(table(x)))
  tmp<-tmp[2:length(tmp)]-tmp[1:(length(tmp)-1)]
  tmp<-tmp[abs(tmp)>.001]
  list(ii=round(x/min(tmp), .00001), k=round(1/min(tmp), .00001))
}
create.index<-function(varnames){
  ii.res<-lapply(dat.cl[,varnames], index.inflate )
  k<-sum(sapply(1:length(ii.res), function(i) ii.res[[i]]$k) )
  inflated.index<-rowSums(sapply(1:length(ii.res), function(i) ii.res[[i]]$ii) )
  inflated.index/k
}
dat.cl$cl_sustainability_score.COMBO<-(dat.cl[,"cl_sustainability_future_score"]*18
                                    +dat.cl[,"cl_sustainability_inst_score"]*16
                                    +dat.cl[,"cl_sustainability_classes_score"]*9
                                    +dat.cl[,"cl_sustainability_MOE_score"]*9
                                    +dat.cl[,"cl_sustainability_shura_score"]*9)/(18+16+9+9)

#### TEACHER

dat.ts$PROVINCE1<-1*(dat.ts$Province=="Parwan")
dat.ts$PROVINCE2<-1*(dat.ts$Province=="Kapisa")
dat.ts$PROVINCE3<-1*(dat.ts$Province=="Herat")
dat.ts$PROVINCE4<-1*(dat.ts$Province=="Bamian")
dat.ts$PROVINCE5<-1*(dat.ts$Province=="Ghur")
dat.ts$PROVINCE6<-1*(dat.ts$Province=="Dykundi")

# assign village size variable to dat
dat.ts$num_hh_needsassmnt<-vil.sizes[dat.ts$VUID,]$num_hh_needsassmnt
dat.ts$ss_wt<-1
dat.ts$wt<-1

# new indexes
dat.ts$q38_r_flip<-  3-dat.ts$q38_r
dat.ts$q38_r_flip<-  dat.ts$q38_r_flip*(dat.ts$q38_r_flip>0)/3
dat.ts$q42_r_flip<-  6-dat.ts$q42_r
dat.ts$q42_r_flip<-  dat.ts$q42_r_flip*(dat.ts$q42_r_flip>0)/6
dat.ts$t_performance_attend_score<- (dat.ts$q38_r_flip+dat.ts$q42_r_flip)/2

# design variables
dat.ts$TREAT<-(dat.ts$TCode>0)*1
dat.ts$HAND <-(dat.ts$HAND==1)*1

# processing existing outcomes 

summary(dat.ts[,c("t_sustainability_inst_score", "t_sustainability_school_score",
               "t_sustainability_MOE_score","t_sustainability_shura_score",
               "t_sustainability_teacher_score", "q50_b", "q51_b")])

lapply(c("q48_b", "q47_b", "q32_r", "q33_b", "q26_r", 
         "q27_r", "q28_r", "q29_r", "q30_r", "q31_r", "q50_b", "q51_b"), function(v) {
  if(max(dat.ts[,v], na.rm=TRUE)>10) {
    dat.ts[!is.na(dat.ts[,v]) & dat.ts[,v]>10,v]<<-10
    dat.ts[,v]<<-dat.ts[,v]/10
  }})
dat.ts$t_sustainability_MOE_score    <-rowSums(dat.ts[,c("q32_r", "q33_b")])/2
dat.ts$t_sustainability_shura_score  <-rowSums(dat.ts[,c("q26_r", "q27_r", "q28_r", "q29_r", "q30_r", "q31_r")])/6
dat.ts$t_sustainability_teacher_score<-rowSums(dat.ts[,c("q50_b", "q51_b")])/2
dat.ts$t_sustainability_score.COMBO  <-rowSums(dat.ts[,c("q48_b", "q47_b", "q32_r", "q33_b", "q26_r",
                                                         "q27_r", "q28_r", "q29_r", "q30_r", "q31_r", "q50_b", "q51_b")])/12
summary(dat.ts[,c("t_motivation_intrinsic_score","t_motivation_material_score")])
dat.ts$t_motivation_score.COMBO<-(dat.ts[,c("t_motivation_intrinsic_score")]+dat.ts[,c("t_motivation_material_score")])/2

summary(dat.ts[,c("t_funds_supplies_score", "t_funds_regularpay_score")])
dat.ts$t_funds_score.COMBO<-rowSums(dat.ts[,c("t_funds_supplies_score", "t_funds_regularpay_score")])/2

##########################
# DATASETS WITH MERGED CAPACITY ASSESSMENT DATA
##########################

dat.hh.ca<-read.dta13("wave4_merged_with_CA_READY.dta")
dat.cl.ca<-read.dta13("wave4_CL_merged_with_CA_READY.dta")
dat.ts.ca<-read.dta13("wave4_TS_merged_with_CA_READY.dta")

#### HOUSEHOLD AND CHILD WITH CAPACITY ASSESSMENT SCORES

#who is not in the endline?:
table(vil.sizes$vuid)[names(table(vil.sizes$vuid))%in%names(table(dat.hh.ca$VUID))==FALSE]
dat.hh.ca$num_hh_needsassmnt<-vil.sizes[dat.hh.ca$VUID,]$num_hh_needsassmnt
vil.surveys<-rowSums(table(dat.hh.ca$VUID, dat.hh.ca$HHID)>0)
dat.hh.ca$num_hh_endline_surveyed<-vil.surveys[dat.hh.ca$VUID]
dat.hh.ca$ss_wt<-dat.hh.ca$num_hh_needsassmnt/dat.hh.ca$num_hh_endline_surveyed

#constructing additional outcomes
dat.hh.ca$ros_attend    <-1*((dat.hh.ca$ros_attend_CBE==1)|(dat.hh.ca$ros_attend_govschool==1))
dat.hh.ca$teacher_attend_score<- -dat.hh.ca$teacher_absentee_score
dat.hh.ca$TREAT<-(dat.hh.ca$TCode>0)*1
dat.hh.ca$HAND <-(dat.hh.ca$HAND==1)*1

#standardize the sum score to make it more interpretable
dat.hh.ca$village_ca_sum_score_std<-(dat.hh.ca$village_ca_sum_score
                                     -mean(dat.hh.ca$village_ca_sum_score[dat.hh.ca$TREAT==1], na.rm=TRUE)
)/sd(dat.hh.ca$village_ca_sum_score[dat.hh.ca$TREAT==1], na.rm=TRUE) 

dat.hh.ca$HAND_village_ca_sum_score_std <- dat.hh.ca$HAND*dat.hh.ca$village_ca_sum_score_std #create interaction variable
dat.hh.ca$HAND_p1 <- dat.hh.ca$HAND*dat.hh.ca$p1 #create interaction variable
dat.hh.ca$HAND_p2 <- dat.hh.ca$HAND*dat.hh.ca$p2 #create interaction variable
dat.hh.ca$HAND_kapisa <- dat.hh.ca$HAND*dat.hh.ca$PROVINCE2 #interaction between Kapisa and treatment variable to account for differential missingness
dat.hh.ca$HAND_parwan <- dat.hh.ca$HAND*dat.hh.ca$PROVINCE1 #interaction between Parwan and treatment variable to account for differential missingness

dat.hh.ca$ros_age611   <-   (dat.hh.ca$ros_age<12)&(dat.hh.ca$ros_age>5)
dat.hh.ca$ros_age1213  <-   (dat.hh.ca$ros_age<14)&(dat.hh.ca$ros_age>11)
dat.hh.ca$ros_age0813  <-   (dat.hh.ca$ros_age<14)&(dat.hh.ca$ros_age>7)

dat.hh.ca$wt          <-((1-dat.hh.ca$TREAT)/.27+(dat.hh.ca$TREAT)/((1-.27)/2))*dat.hh.ca$ss_wt
t.hhid<-table(dat.hh.ca$HHID, useNA = "always")
uid<-(cbind(c(1:length(dat.hh.ca$HHID)), dat.hh.ca$HHID, dat.hh.ca$CHID))[order(dat.hh.ca$HHID),]
within.hh.id<-cbind(as.numeric(rep(names(t.hhid), times=t.hhid)) 
                    ,as.vector(do.call(c,  sapply(t.hhid, function(nhh) c(1:nhh))))
)
table(as.vector(uid[,2])==as.vector(within.hh.id[,1]))
uid<-cbind(uid, within.hh.id[,2])
table(uid[order(uid[,1]),3]==dat.hh.ca$CHID)
dat.hh.ca$within.hh.id<-uid[order(uid[,1]),4]


#### COMMUNITY LEADER WITH CAPACITY ASSESSMENT SCORES

dat.cl.ca$PROVINCE1<-1*(dat.cl.ca$Province=="Parwan")
dat.cl.ca$PROVINCE2<-1*(dat.cl.ca$Province=="Kapisa")
dat.cl.ca$PROVINCE3<-1*(dat.cl.ca$Province=="Herat")
dat.cl.ca$PROVINCE4<-1*(dat.cl.ca$Province=="Bamian")
dat.cl.ca$PROVINCE5<-1*(dat.cl.ca$Province=="Ghur")
dat.cl.ca$PROVINCE6<-1*(dat.cl.ca$Province=="Dykundi")

#who is not in the endline?:
table(vil.sizes$vuid)[names(table(vil.sizes$vuid))%in%names(table(dat.cl.ca$VUID))==FALSE]
#assign village size variable to dat
dat.cl.ca$num_hh_needsassmnt<-vil.sizes[dat.cl.ca$VUID,]$num_hh_needsassmnt
dat.cl.ca$ss_wt<-1
dat.cl.ca$wt<-1

# constructing additional outcomes

dat.cl.ca$TREAT<-(dat.cl.ca$TCode>0)*1
dat.cl.ca$HAND <-(dat.cl.ca$HAND==1)*1

#standardize the sum score to make it more interpretable
dat.cl.ca$village_ca_sum_score_std<-(dat.cl.ca$village_ca_sum_score
                                     -mean(dat.cl.ca$village_ca_sum_score[dat.cl.ca$TREAT==1], na.rm=TRUE)
)/sd(dat.cl.ca$village_ca_sum_score[dat.cl.ca$TREAT==1], na.rm=TRUE) 

dat.cl.ca$HAND_village_ca_sum_score_std <- dat.cl.ca$HAND*dat.cl.ca$village_ca_sum_score_std #create interaction variable
dat.cl.ca$HAND_p1<- dat.cl.ca$HAND*dat.cl.ca$p1 #create interaction variable
dat.cl.ca$HAND_p2 <- dat.cl.ca$HAND*dat.cl.ca$p2 #create interaction variable
dat.cl.ca$HAND_kapisa <- dat.cl.ca$HAND*dat.cl.ca$PROVINCE2 #interaction between Kapisa and treatment variable to account for differential missingness
dat.cl.ca$HAND_parwan <- dat.cl.ca$HAND*dat.cl.ca$PROVINCE1 #interaction between Parwan and treatment variable to account for differential missingness

#### TEACHER WITH CAPACITY ASSESSMENT SCORES

dat.ts.ca$PROVINCE1<-1*(dat.ts.ca$Province=="Parwan")
dat.ts.ca$PROVINCE2<-1*(dat.ts.ca$Province=="Kapisa")
dat.ts.ca$PROVINCE3<-1*(dat.ts.ca$Province=="Herat")
dat.ts.ca$PROVINCE4<-1*(dat.ts.ca$Province=="Bamian")
dat.ts.ca$PROVINCE5<-1*(dat.ts.ca$Province=="Ghur")
dat.ts.ca$PROVINCE6<-1*(dat.ts.ca$Province=="Dykundi")

table(vil.sizes$vuid)[names(table(vil.sizes$vuid))%in%names(table(dat.ts.ca$VUID))==FALSE]
dat.ts.ca$num_hh_needsassmnt<-vil.sizes[dat.ts.ca$VUID,]$num_hh_needsassmnt
dat.ts.ca$ss_wt<-1
dat.ts.ca$wt<-1

# constructing additional outcomes

dat.ts.ca$TREAT<-(dat.ts.ca$TCode>0)*1
dat.ts.ca$HAND <-(dat.ts.ca$HAND==1)*1

#standardize the sum score to make it more interpretable
dat.ts.ca$village_ca_sum_score_std<-(dat.ts.ca$village_ca_sum_score
                                     -mean(dat.ts.ca$village_ca_sum_score[dat.ts.ca$TREAT==1], na.rm=TRUE)
)/sd(dat.ts.ca$village_ca_sum_score[dat.ts.ca$TREAT==1], na.rm=TRUE) 

dat.ts.ca$HAND_village_ca_sum_score_std <- dat.ts.ca$HAND*dat.ts.ca$village_ca_sum_score_std #create interaction variable
dat.ts.ca$HAND_p1 <- dat.ts.ca$HAND*dat.ts.ca$p1 #create interaction variable
dat.ts.ca$HAND_p2 <- dat.ts.ca$HAND*dat.ts.ca$p2 #create interaction variable
dat.ts.ca$HAND_kapisa <- dat.ts.ca$HAND*dat.ts.ca$PROVINCE2 #interaction between Kapisa and treatment variable to account for differential missingness
dat.ts.ca$HAND_parwan <- dat.ts.ca$HAND*dat.ts.ca$PROVINCE1 #interaction between Parwan and treatment variable to account for differential missingness

#new indexes
dat.ts.ca$q38_r_flip<-  3-dat.ts.ca$q38_r
dat.ts.ca$q38_r_flip<-  dat.ts.ca$q38_r_flip*(dat.ts.ca$q38_r_flip>0)/3
dat.ts.ca$q42_r_flip<-  6-dat.ts.ca$q42_r
dat.ts.ca$q42_r_flip<-  dat.ts.ca$q42_r_flip*(dat.ts.ca$q42_r_flip>0)/6
dat.ts.ca$t_performance_attend_score<- (dat.ts.ca$q38_r_flip+dat.ts.ca$q42_r_flip)/2

dat.ts.ca$t_sustainability_MOE_score    <-rowSums(dat.ts.ca[,c("q32_r", "q33_b")])/2
dat.ts.ca$t_sustainability_shura_score  <-rowSums(dat.ts.ca[,c("q26_r", "q27_r", "q28_r", "q29_r", "q30_r", "q31_r")])/6
dat.ts.ca$t_sustainability_teacher_score<-rowSums(dat.ts.ca[,c("q50_b", "q51_b")])/2
dat.ts.ca$t_sustainability_score.COMBO  <-rowSums(dat.ts.ca[,c("q48_b", "q47_b", "q32_r", "q33_b", "q26_r", "q27_r", "q28_r", "q29_r", "q30_r", "q31_r", "q50_b", "q51_b")])/12
dat.ts.ca$t_motivation_score.COMBO<-(dat.ts.ca[,c("t_motivation_intrinsic_score")]+dat.ts.ca[,c("t_motivation_material_score")])/2
dat.ts.ca$t_funds_score.COMBO<-rowSums(dat.ts.ca[,c("t_funds_supplies_score", "t_funds_regularpay_score")])/2

##########################
#  SETTING UP COVARIATES
##########################

cov1.hh<-c("int_lang_pashto", "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik"
           , "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "hh_num"
           ,  "hh_jeribs",  "hh_animal_sheep",  "school_km")
cov1.hh<-cov1.hh[cov1.hh%in%names(dat.hh)]
cov2.hh<-c(cov1.hh, "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read"
           , "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government",
           "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000", 
           "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs", 
           "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children", 
           "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5", "PROVINCE6")
cov2.hh<-cov2.hh[cov2.hh%in%names(dat.hh)]
cov1.child<-c("ros_hhheadchild", "ros_girl", "ros_age", cov1.hh)
cov2.child<-c("ros_hhheadchild", "ros_girl", "ros_age", cov2.hh)

cov1.cl<-c("int_lang_pashto", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "hh_num"
           ,  "hh_jeribs",  "hh_animal_sheep",  "school_km")
cov1.cl<-cov1.cl[cov1.cl%in%names(dat.cl)]
cov2.cl<-c(cov1.cl, "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read"
           , "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government" ,"hhhead_edu_university"
           , "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000", "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth"
           , "hh_landown", "hh_children", "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5", "PROVINCE6")
cov2.cl<-cov2.cl[cov2.cl%in%names(dat.cl)]

cov1.ts<-c("int_lang_pashto", "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik"
           , "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "hh_num"
           ,  "hh_jeribs",  "hh_animal_sheep",  "school_km")
cov1.ts<-cov1.ts[cov1.ts%in%names(dat.ts)]
cov2.ts<-c(cov1.ts, "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read"
           , "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government" ,"hhhead_edu_university"
           , "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000", "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth"
           , "hh_landown", "hh_children", "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5", "PROVINCE6")
cov2.ts<-cov2.ts[cov2.ts%in%names(dat.ts)]


#mean impute
meanimpute1<-function(v){
  dat.hh[is.na(dat.hh[,v]),v]<<-mean(dat.hh[,v], na.rm=TRUE)
}
lapply(cov2.hh, meanimpute1)

meanimpute2<-function(v){
  dat.cl[is.na(dat.cl[,v]),v]<<-mean(dat.cl[,v], na.rm=TRUE)
}
lapply(cov2.cl, meanimpute2)

meanimpute3<-function(v){
  dat.ts[is.na(dat.ts[,v]),v]<<-mean(dat.ts[,v], na.rm=TRUE)
}
lapply(cov2.ts, meanimpute3)

dm<-function(x, na.impute=FALSE){
  x.dm<-x-mean(x, na.rm=TRUE)
  if(na.impute==TRUE){
    x.dm[is.na(x.dm)]<-0
  }
  sd.dm<-sd(x.dm, na.rm=TRUE)
  if(sd.dm>0){
    x.dm<-x.dm/sd.dm
  }
  x.dm
}

# function for summary statistics 
jmsummary<-function(x){
  cbind(N=sum(!is.na(x)),
    mean=mean(x, na.rm=TRUE), sd=sd(x, na.rm=TRUE)
        , min=min(x, na.rm=TRUE), max=max(x, na.rm=TRUE)
        , binary=1*((min(x, na.rm=TRUE)==0)&(max(x, na.rm=TRUE)==1)&(length(table(x))==2))
        )
}

# control group standardizing functions

wtd.mean.sd<-function(x, w){
  g<- !is.na(x*w)
  x<- x[g]
  w<- w[g]
  m<-sum(x*w)/sum(w)
  s<-sqrt(sum(w*((x-m)^2))/sum(w))
  list(mean=m, sd=s)
}


hh_sd <- function(x){
  x_sd <-wtd.mean.sd(x[within_hh_dat$HAND==0&within_hh_dat$TREAT==1], 
                    within_hh_dat$wt[within_hh_dat$HAND==0&within_hh_dat$TREAT==1])
  x_out <-  (x-x_sd$mean)/x_sd$sd
  return(x_out)
}


cl_sd <- function(x){
  x_out <- (x-mean(x[dat.cl$HAND==0], na.rm=TRUE))/sd(x[dat.cl$HAND==0], na.rm=TRUE)
  return(x_out)
}

ts_sd <- function(x){
  x_out <-(x-mean(x[dat.ts$HAND==0], na.rm=TRUE))/sd(x[dat.ts$HAND==0], na.rm=TRUE)
  return(x_out)
}

# table formatting function

addParens <- function(x,y){paste0("(",round(x,y),")")}

##########################
######  ANALYSIS  ########
##########################

# NB: The variable "TREAT" refers to Phase 1 treatment group, while
# the variable "HAND" refers to Phase 2 handover to sustainability model.
# Therefore, "TREAT" defines the relevant subsample for the Phase 2 study,
# and "HAND" indicates among those, whether they were randonly assigned
# to handover to the sustainability model and is thus the treatment
# variable for Phase 2.

# Analysis data subsets

dat.hh <- subset(dat.hh, TREAT==1) # only those that were treated in Phase 1
children_dat <- subset(dat.hh, ros_age0813==1)
within_hh_dat <- subset(dat.hh, within.hh.id==1)
dat.cl <- subset(dat.cl, TREAT==1) # only those that were treated in Phase 1
dat.ts <- subset(dat.ts, TREAT==1) # only those that were treated in Phase 1
CARE_cl <- subset(dat.cl, NGO==1)
CRS_cl <- subset(dat.cl, NGO==2)

##############################################################################
### TABLE 1 : SUMMARY STATISTICS FOR EQUIVALENCY AND NON-EQUIVALENCY OUTCOMES
##############################################################################

# children, households, community leader, teacher

#children
stat1<-jmsummary(children_dat$ros_attend)
rownames(stat1) <- "Attendance"

stat2<-jmsummary(children_dat$std_mathread)
rownames(stat2) <- "Math and reading score"

# households
within_hh_dat$std_satisfaction_access_score <- hh_sd(within_hh_dat$satisfaction_access_score)
stat3<-jmsummary(within_hh_dat$std_satisfaction_access_score)
rownames(stat3) <- "Household satisfaction"

within_hh_dat$std_sustainability_confidence_score <- hh_sd(within_hh_dat$sustainability_confidence_score)
stat4<-jmsummary(within_hh_dat$std_sustainability_confidence_score)
rownames(stat4) <- "Confidence in local institutions"

within_hh_dat$std_teacher_attend_score <- hh_sd(within_hh_dat$teacher_attend_score)
stat5<-jmsummary(within_hh_dat$std_teacher_attend_score)
rownames(stat5) <- "Teacher attendance score"

within_hh_dat$std_teacher_perception_score <- hh_sd(within_hh_dat$teacher_perception_score)
stat6<-jmsummary(within_hh_dat$std_teacher_perception_score)
rownames(stat6) <- "Community perception of teacher quality"

# community leaders endline
dat.cl$std_cl_satisfaction_access_score <- cl_sd(dat.cl$cl_satisfaction_access_score)
stat7<-jmsummary(dat.cl$std_cl_satisfaction_access_score)
rownames(stat7) <- "Perceived access to quality education"

dat.cl$std_cl_funds_supplies_score <- cl_sd(dat.cl$cl_funds_supplies_score)
stat8<-jmsummary(dat.cl$std_cl_funds_supplies_score)
rownames(stat8) <- "Classroom supplies score"

dat.cl$std_cl_sustainability_score.COMBO <- cl_sd(dat.cl$cl_sustainability_score.COMBO)
stat9<-jmsummary(dat.cl$std_cl_sustainability_score.COMBO)
rownames(stat9) <- "Combined sustainability index"

dat.cl$std_cl_sustainability_future_score <- cl_sd(dat.cl$cl_sustainability_future_score)
stat10<-jmsummary(dat.cl$std_cl_sustainability_future_score)
rownames(stat10) <- "Community provision for future classes"

dat.cl$std_cl_sustainability_inst_score <- cl_sd(dat.cl$cl_sustainability_inst_score)
stat11<-jmsummary(dat.cl$std_cl_sustainability_inst_score)
rownames(stat11) <- "Confidence in community institutions"

dat.cl$std_cl_sustainability_classes_score <- cl_sd(dat.cl$cl_sustainability_classes_score)
stat12<-jmsummary(dat.cl$std_cl_sustainability_classes_score)
rownames(stat12) <- "Confidence that school will be sustained"

dat.cl$std_cl_sustainability_MOE_score <- cl_sd(dat.cl$cl_sustainability_MOE_score)
stat13<-jmsummary(dat.cl$std_cl_sustainability_MOE_score)
rownames(stat13) <- "MOE provisions for funding teachers"

dat.cl$std_cl_sustainability_shura_score <- cl_sd(dat.cl$cl_sustainability_shura_score)
stat14<-jmsummary(dat.cl$std_cl_sustainability_shura_score)
rownames(stat14) <- "Shura provisions for future classes"

# teachers

dat.ts$std_t_funds_score.COMBO <-ts_sd(dat.ts$t_funds_score.COMBO)
stat15<-jmsummary(dat.ts$std_t_funds_score.COMBO)
rownames(stat15) <- "Combined fund application index"

dat.ts$std_t_funds_supplies_score <-ts_sd(dat.ts$t_funds_supplies_score)
stat16<-jmsummary(dat.ts$std_t_funds_supplies_score)
rownames(stat16) <- "Classroom supplies"

dat.ts$std_t_motivation_score.COMBO <-ts_sd(dat.ts$t_motivation_score.COMBO)
stat17<-jmsummary(dat.ts$std_t_motivation_score.COMBO)
rownames(stat17) <- "Combined motivation index"

dat.ts$std_t_motivation_intrinsic_score <-ts_sd(dat.ts$t_motivation_intrinsic_score)
stat30<-jmsummary(dat.ts$std_t_motivation_intrinsic_score)
rownames(stat30) <- "Intrinsic motivation"

dat.ts$std_t_motivation_material_score <-ts_sd(dat.ts$t_motivation_material_score)
stat31<-jmsummary(dat.ts$std_t_motivation_material_score)
rownames(stat31) <- "Material motivation and satisfaction"

dat.ts$std_t_funds_regularpay_score <-ts_sd(dat.ts$t_funds_regularpay_score)
stat32<-jmsummary(dat.ts$std_t_funds_regularpay_score)
rownames(stat32) <- "Whether teacher is being paid regularly"

dat.ts$std_t_sustainability_score.COMBO <-ts_sd(dat.ts$t_sustainability_score.COMBO)
stat18<-jmsummary(dat.ts$std_t_sustainability_score.COMBO)
rownames(stat18) <- "Combined sustainability index"

stat19<-jmsummary(dat.ts$t_sustainability_inst_score)
rownames(stat19) <- "Confidence in local community institutions"

stat20<-jmsummary(dat.ts$t_sustainability_school_score)
rownames(stat20) <- "Confidence that school will be sustained"

dat.ts$std_t_sustainability_MOE_score <-ts_sd(dat.ts$t_sustainability_MOE_score)
stat21<-jmsummary(dat.ts$std_t_sustainability_MOE_score)
rownames(stat21) <- "Proactive management from MOE"

dat.ts$std_t_sustainability_shura_score <-ts_sd(dat.ts$t_sustainability_shura_score)
stat22<-jmsummary(dat.ts$std_t_sustainability_shura_score)
rownames(stat22) <- "Proactive management from shuras"

dat.ts$std_t_sustainability_teacher_score <-ts_sd(dat.ts$t_sustainability_teacher_score)
stat23<-jmsummary(dat.ts$std_t_sustainability_teacher_score)
rownames(stat23) <- "Teacher plans to remain CBE teacher"


# community leader follow-up
stat24<-jmsummary(CARE_cl$phone_sustain_want_score_rev)
rownames(stat24) <- "Community desire to continue CBE"

stat25<-jmsummary(CARE_cl$sustain.index_std)
rownames(stat25) <- "Combined sustainability index"

stat26<-jmsummary(CARE_cl$phone_sustain_initiative_score_std)
rownames(stat26) <- "Initiative to have CBE sustained"

stat27<-jmsummary(CARE_cl$phone_sustain_provisions_score_std)
rownames(stat27) <- "Provisions for sustainability without NGO"

stat28<-jmsummary(CARE_cl$phone_sustain_confidence_score)
rownames(stat28) <- "Confidence that school will sustain"

stat29<-jmsummary(CARE_cl$phone_sustain_2018_score)
rownames(stat29) <- "Continued CBE operations in spring 2018"

combined.sum.stats<-cbind(rbind(stat1, stat2, stat3, stat4, stat5, 
                          stat6, stat7, stat8, stat9, stat10,
                          stat11, stat12, stat13, stat14, stat15, 
                          stat16, stat17, stat30, stat31, stat32,
                          stat18, stat19, stat20,
                          stat21, stat22, stat23, stat24, stat25,
                          stat26, stat27, stat28, stat29),rep(NA,32))
library(xtable)
Table1_Output<-xtable(combined.sum.stats,
                      digits = c(0,0,3,3,3,3,0,0),
                      caption = "\\label{tab:summarystatistics} Summary Statistics for Equivalency and Non-Equivalency Outcomes")
addtorow <- list()
addtorow$pos <- list(0, 2, 2,6,6,14,14,26,26)
addtorow$command <- c("{\\bf Children (Aged 8-13) Outcomes}  &  &  &  & &  & &\\\\\n",
                      "\\\\\n",
                      "{\\bf Household Outcomes}  &  &  &  & &  & & \\\\\n",
                      "\\\\\n",
                      "{\\bf Community Leader Outcomes}  &  &  &  & &  & & \\\\\n",
                      "\\\\\n",
                      "{\\bf Teacher Outcomes}  &  &  &  & &  & & \\\\\n",
                      "\\\\\n",
                      "{\\bf Follow-up Sustainability Outcomes}  &  &  &  & &  & & \\\\\n")
sink(file="tabs-figs/summary_statistics_tomod.tex")
print(Table1_Output, 
      add.to.row = addtorow,
      caption.placement = "top")
sink()

#information on the outcome type and SESOI added to table by hand 

# Based on the cost information, this is the SESOI for outcomes with no
# phase 1 treatment effect estimates, based on the 0.30SD rule of thumb:

sesoi_gen <- -0.30*(1-(3457/6439))

# covariates 
XX_children<-as.matrix(cbind(children_dat[, c("TREAT", "HAND")], sapply(children_dat[, cov2.child], dm)))
XX_hh<-as.matrix(cbind(within_hh_dat[, c("TREAT", "HAND")], sapply(within_hh_dat[, cov2.hh], dm)))
XX_cl<-as.matrix(cbind(dat.cl[, c("TREAT", "HAND")], sapply(dat.cl[, cov1.cl], dm)))
cv_ts<-dm(dat.ts[, cov1.ts])
XX_ts<-as.matrix(cbind(dat.ts[, c("TREAT", "HAND")], cv_ts))
XX_CARE_cl<-as.matrix(cbind(CARE_cl[, c("TREAT", "HAND")], sapply(CARE_cl[, cov1.cl], dm)))


##############################################################################
#### FIGURE 3: PRIMARY EQUIVALENCY OUTCOMES
##############################################################################

# set up 
if(("clubSandwich"%in%installed.packages())==FALSE){
  install.packages("clubSandwich")
}
library(clubSandwich)


# Regression 1: child equivalence regression, aged 8-13 attendance outcome with child cov2 list

y.tr1 <- children_dat$ros_attend
lm1<-lm( formula(paste("y.tr1", "XX_children", sep="~")),  weights=children_dat$wt)
res1<-coef_test(lm1, vcov=vcovCR(lm1, cluster=children_dat$CLUSTER, type="CR2"))
print(res1)

#full results with all covariates [for appendix]
res1full<-as.data.frame(res1)

#main results without all the covariates [for main body of paper]
res1<-as.data.frame(res1[2,]) # keep second row of output 

# add in columns on the sesoi for ros_attend
sesoi1<-c(-.463*0.1385)
z1<-(res1[,"beta"]-sesoi1)/res1[,"SE"]
p_sesoi1=pt(-z1, df = res1[,"df_Satt"])

# add in t_Satt_citical
t1  <-sapply(res1$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for ros_attend
res1<-cbind(res1, sesoi=sesoi1, p_sesoi=p_sesoi1, t_Satt_crit=t1, ci_l=res1$beta-t1*res1[,"SE"], 
            ci_u=res1[,"beta"]+t1*res1[,"SE"],
           coverage=0.9, N=length(lm1$residuals))
rownames(res1)<-paste(rownames(res1), 'ros_attend')
res1

# Regression 2: child equivalence regression, aged 8-13 test scores with child cov2 list

y.tr2 <- children_dat[, "std_mathread"]
lm2<-lm(formula(paste("y.tr2", "XX_children", sep="~")),  weights=children_dat$wt)
res2<-coef_test(lm2, vcov=vcovCR(lm2, cluster=children_dat$CLUSTER, type="CR2"))
print(res2)

#full results with all covariates [for appendix]
res2full<-as.data.frame(res2)

#main results without all the covariates [for main body of paper]
res2<-as.data.frame(res2[2,]) # keep second row of output 

# add in columns on the sesoi for std_mathread
sesoi2<-c(-.463*0.2840)
z2<-(res2[,"beta"]-sesoi2)/res2[,"SE"]
p_sesoi2=pt(-z2, df = res2[,"df_Satt"])

# add in t_Satt_citical
t2 <-sapply(res2$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for std_mathread
res2<-cbind(res2, sesoi=sesoi2, p_sesoi=p_sesoi2, t_Satt_crit=t2, ci_l=res2$beta-t2*res2[,"SE"],
            ci_u=res2[,"beta"]+t2*res2[,"SE"],
           coverage=0.9, N=length(lm2$residuals))
rownames(res2)<-paste(rownames(res2), 'std_mathread')
res2

# Regression 3: household equivalence regression, satisfaction with access outcome

y.tr3 <- within_hh_dat$std_satisfaction_access_score
lm3<-lm( formula(paste("y.tr3", "XX_hh", sep="~")),  weights=within_hh_dat$wt)
res3<-coef_test(lm3, vcov=vcovCR(lm3, cluster=within_hh_dat$CLUSTER, type="CR2"))
print(res3)

#full results with all covariates [for appendix]
res3full<-as.data.frame(res3)

#main results without all the covariates [for main body of paper]
res3<-as.data.frame(res3[2,]) # keep second row of output 

# add in columns on the sesoi for satisfaction_access_score
sesoi3<- sesoi_gen
z3<-(res3[,"beta"]-sesoi3)/res3[,"SE"]
p_sesoi3=pt(-z3, df = res3[,"df_Satt"])

# add in t_Satt_citical
t3 <-sapply(res3$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for satisfaction_access_score
res3<-cbind(res3, sesoi=sesoi3, p_sesoi=p_sesoi3, t_Satt_crit=t3, ci_l=res3$beta-t3*res3[,"SE"],
            ci_u=res3[,"beta"]+t3*res3[,"SE"],
            coverage=0.9, N=length(lm3$residuals))
rownames(res3)<-paste(rownames(res3), 'satisfaction_access_score')
res3 # shows raw output for what is in the figure for household satisfaction

# combine all the main hh and child results in figure
primary_equiv_results <- rbind(res1, res2, res3)
print(primary_equiv_results) 

prim_equi_for_graph <- data.frame(ATE=primary_equiv_results$beta,
                                  lower=primary_equiv_results$ci_l,
                                  upper=primary_equiv_results$ci_u,
                                  SESOI=primary_equiv_results$sesoi,
                                  p_sesoi=primary_equiv_results$p_sesoi)

rownames(prim_equi_for_graph) <- c("attendance",
                                    "math_reading",
                                   "household_satisfaction")

write.csv(prim_equi_for_graph,
          file="tabs-figs/main_results.csv",
          row.names = TRUE)

#####################
# VISUAL RESULTS
#####################

library(gridExtra)

dat<-read.csv("tabs-figs/main_results.csv")

##############
#MAIN RESULTS#
##############

# separate then combine
#attendance
d=data.frame(y="", 
             ATE=c(dat$ATE[1]), lower=c(dat$lower[1]), 
             upper=c(dat$upper[1]))
plot1<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.2, xmax=dat$SESOI[1], ymin=0, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.2,round(dat$SESOI[1], 3),round(dat$ATE[1], 3),0,0.1,0.2), labels=c("",paste0(round(dat$SESOI[1], 3)),paste0(round(dat$ATE[1], 3)),"","0.1","0.2"), 
                     limits=c(-0.2,0.2), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=20), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat$SESOI[1]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.16, y = 1, label = paste0("p-SESOI = ",round(dat$p_sesoi[1], 3),"**"), size = 5) + 
  ggtitle("Attendance (percentage points)") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.2, 0.22))

#math and reading score
d=data.frame(y="", 
             ATE=c(dat$ATE[2]), lower=c(dat$lower[2]), 
             upper=c(dat$upper[2]))
plot2<-ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower), 
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.2, xmax=dat$SESOI[2], ymin=0, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.2,round(dat$SESOI[2], 3),round(dat$ATE[2], 3),0,0.1,0.2), labels=c("",paste0(round(dat$SESOI[2], 3)),paste0(round(dat$ATE[2], 3)),"","0.1","0.2"), 
                     limits=c(-0.2,0.2), expand = c(0, 0))  + 
  theme_classic() + ylab("") + xlab("\n") + theme(
    axis.title.x = element_text(color="black", size=8, face="bold"), 
    axis.text.x =element_text(size=20), 
    axis.ticks.y = element_blank()) + 
  geom_vline(xintercept=c(dat$SESOI[2]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.16, y = 1, label = paste0("p-SESOI = ",round(dat$p_sesoi[2], 3),"**"), size = 5) + 
  ggtitle("Math and Reading Score (control group SDs)") +
  theme(plot.title = element_text(hjust = 0.5)) + 
  theme(plot.title = element_text(size = 15, face = "bold")) +
  coord_cartesian(xlim = c(-0.2, 0.22))

#household satisfaction 
d=data.frame(y="", 
             ATE=c(dat$ATE[3]), lower=c(dat$lower[3]), 
             upper=c(dat$upper[3]))
plot3<-ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower), 
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.2, xmax=dat$SESOI[3], ymin=0, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.2,dat$SESOI[3],-0.1,dat$ATE[3],0,0.1,0.2), labels=c("",paste0(round(dat$SESOI[3], 3)),"-0.1",paste0(round(dat$ATE[3], 3)),"","0.1","0.2"), 
                     limits=c(-0.2,0.2), expand = c(0, 0)) + 
  theme_classic() + ylab("") + xlab("\n Treatment Effect of Sustainability Model Relative to NGO") + theme(
    axis.title.x = element_text(color="black", size=15), 
    axis.text.x =element_text(size=20), 
    axis.ticks.y = element_blank()) + 
  geom_vline(xintercept=c(dat$SESOI[3]), linetype=c("dotted"), color=c("black")) +
  scale_linetype_manual(name = 'lines',
                        values = c('dotted' = 1,
                                   'dotted' = 1),
                        guide = guide_legend(override.aes = list(colour = c('black',
                                                                            'blue'))))+
  annotate("text", x = 0.16, y = 1, label = paste0("p-SESOI = ",round(dat$p_sesoi[3], 3),"**"), size = 5) + 
  ggtitle("Household Satisfaction (control group SDs)") +
  theme(plot.title = element_text(hjust = 0.5)) +    
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.2, 0.22))

pdf(file="tabs-figs/primary_results_equiv.pdf",
    height=6, width=12)
grid.arrange(plot1, plot2, plot3, ncol=1)
dev.off()

##############################################################################
#### FIGURE 4: TEST OF POTENTIAL AGENCY ISSUES 
##############################################################################

## Household outcome 1: teacher attendance

y.tr4 <- within_hh_dat$std_teacher_attend_score
lm4<-lm( formula(paste("y.tr4", "XX_hh", sep="~")),  weights=within_hh_dat$wt)
res4<-coef_test(lm4, vcov=vcovCR(lm4, cluster=within_hh_dat$CLUSTER, type="CR2"))
print(res4)

#full results with all covariates [for appendix]
res4full<-as.data.frame(res4)

#main results without all the covariates [for main body of paper]
res4<-as.data.frame(res4[2,]) # keep second row of output 

# add in columns on the sesoi for teacher_attend_score
sesoi4<- sesoi_gen
z4<-(res4[,"beta"]-sesoi4)/res4[,"SE"]
p_sesoi4=pt(-z4, df = res4[,"df_Satt"])

# add in t_Satt_citical
t4 <-sapply(res4$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for teacher_attend_score
res4<-cbind(res4, sesoi=sesoi4, p_sesoi=p_sesoi4, t_Satt_crit=t4, ci_l=res4$beta-t4*res4[,"SE"],
            ci_u=res4[,"beta"]+t4*res4[,"SE"],
            coverage=0.9, N=length(lm4$residuals))
rownames(res4)<-paste(rownames(res4), 'teacher_attend_score')
res4

# Household outcome 2: perception of teacher quality  

y.tr5<-within_hh_dat$std_teacher_perception_score
lm5<-lm( formula(paste("y.tr5", "XX_hh", sep="~")),  weights=within_hh_dat$wt)
res5<-coef_test(lm5, vcov=vcovCR(lm5, cluster=within_hh_dat$CLUSTER, type="CR2"))
print(res5)

#full results with all covariates [for appendix]
res5full<-as.data.frame(res5)

#main results without all the covariates [for main body of paper]
res5<-as.data.frame(res5[2,]) # keep second row of output 

# add in columns on the sesoi for teacher_perception_score
sesoi5<- sesoi_gen
z5<-(res5[,"beta"]-sesoi5)/res5[,"SE"]
p_sesoi5=pt(-z5, df = res5[,"df_Satt"])

# add in t_Satt_citical
t5 <-sapply(res5$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for teacher_perception_score
res5<-cbind(res5, sesoi=sesoi5, p_sesoi=p_sesoi5, t_Satt_crit=t5, ci_l=res5$beta-t5*res5[,"SE"],
            ci_u=res5[,"beta"]+t5*res5[,"SE"],
            coverage=0.9, N=length(lm5$residuals))
rownames(res5)<-paste(rownames(res5), 'teacher_perception_score')
res5

# Household outcome 3: confidence in local institutions 

y.tr6<-within_hh_dat$std_sustainability_confidence_score
lm6<-lm( formula(paste("y.tr6", "XX_hh", sep="~")),  weights=within_hh_dat$wt)
res6<-coef_test(lm6, vcov=vcovCR(lm6, cluster=within_hh_dat$CLUSTER, type="CR2"))
print(res6)

#full results with all covariates [for appendix]
res6full<-as.data.frame(res6)

#main results without all the covariates [for main body of paper]
res6<-as.data.frame(res6[2,]) # keep second row of output 

# add in columns on the sesoi for sustainability_confidence_score
sesoi6<- NA
z6<-(res6[,"beta"]-sesoi6)/res6[,"SE"]
p_sesoi6=pt(-z6, df = res6[,"df_Satt"])

# add in t_Satt_citical
t6 <-sapply(res6$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for sustainability_confidence_score
res6<-cbind(res6, sesoi=sesoi6, p_sesoi=p_sesoi6, t_Satt_crit=t6, ci_l=res6$beta-t6*res6[,"SE"],
            ci_u=res6[,"beta"]+t6*res6[,"SE"],
            coverage=0.9, N=length(lm6$residuals))
rownames(res6)<-paste(rownames(res6), 'sustainability_confidence_score')
res6

# Community leader outcome 1: classroom supplies

y.tr7<-dat.cl$std_cl_funds_supplies_score
lm7<-lm( formula(paste("y.tr7", "XX_cl", sep="~")),  weights=dat.cl$wt)
res7<-coef_test(lm7, vcov=vcovCR(lm7, cluster=dat.cl$CLUSTER, type="CR2"))
print(res7)

#full results with all covariates [for appendix]
res7full<-as.data.frame(res7)

#main results without all the covariates [for main body of paper]
res7<-as.data.frame(res7[2,]) # keep second row of output 

sesoi7<- sesoi_gen
z7<-(res7[,"beta"]-sesoi7)/res7[,"SE"]
p_sesoi7=pt(-z7, df = res7[,"df_Satt"])
t7  <-sapply(res7$df, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.90
res7<-cbind(res7, sesoi=sesoi7, p_sesoi=p_sesoi7, t_Satt_crit=t7, ci_l=res7$beta-t7*res7[,"SE"], ci_u=res7[,"beta"]+t7*res7[,"SE"], 
            coverage=0.9, N=length(lm7$residuals))

rownames(res7)<-paste(rownames(res7),"cl_funds_supplies_score")
res7

# Teacher outcome 1: combined fund application index

y.tr8 <- dat.ts$std_t_funds_score.COMBO
lm8<-lm( formula(paste("y.tr8", "XX_ts", sep="~")),  weights=dat.ts$wt)
res8<-coef_test(lm8, vcov=vcovCR(lm8, cluster=dat.ts$CLUSTER, type="CR2"))
print(res8)

#full results covariates [for appendix]
res8full<-as.data.frame(res8)

#main results without all the covariates [for main body of paper]
res8<-as.data.frame(res8[2,]) # keep second row of output 

sesoi8<- sesoi_gen
z8<-(res8[,"beta"]-sesoi8)/res8[,"SE"]
p_sesoi8=pt(-z8, df = res8[,"df_Satt"])

t8 <-sapply(res8$df, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.9
res8<-cbind(res8, sesoi=sesoi8, p_sesoi=p_sesoi8, t_Satt_crit=t8, ci_l=res8$beta-t8*res8[,"SE"], ci_u=res8[,"beta"]+t8*res8[,"SE"], 
             coverage=0.9, N=length(lm8$residuals))
rownames(res8)<-paste(rownames(res8),"t_funds_score.COMBO")
res8

# Teacher outcome 2: classroom supplies

y.tr9 <- dat.ts$std_t_funds_supplies_score
lm9<-lm( formula(paste("y.tr9", "XX_ts", sep="~")),  weights=dat.ts$wt)
res9<-coef_test(lm9, vcov=vcovCR(lm9, cluster=dat.ts$CLUSTER, type="CR2"))
print(res9)

#full results [for appendix]
res9full<-as.data.frame(res9)

#main results without all the covariates [for main body of paper]
res9<-as.data.frame(res9[2,]) # keep second row of output 

sesoi9<- sesoi_gen
z9<-(res9[,"beta"]-sesoi9)/res9[,"SE"]
p_sesoi9=pt(-z9, df = res9[,"df_Satt"])

t9  <-sapply(res9$df, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.9
res9<-cbind(res9, sesoi=sesoi9, p_sesoi=p_sesoi9, t_Satt_crit=t9, ci_l=res9$beta-t9*res9[,"SE"], ci_u=res9[,"beta"]+t9*res9[,"SE"], 
            coverage=0.9, N=length(lm9$residuals))
rownames(res9)<-paste(rownames(res9),"t_funds_supplies_score")
res9

# Teacher outcome 3: combined motivation index

y.tr10 <- dat.ts$std_t_motivation_score.COMBO
lm10<-lm( formula(paste("y.tr10", "XX_ts", sep="~")),  weights=dat.ts$wt)
res10<-coef_test(lm10, vcov=vcovCR(lm10, cluster=dat.ts$CLUSTER, type="CR2"))
print(res10)

#full results [for appendix]
res10full<-as.data.frame(res10)

#main results without all the covariates [for main body of paper]
res10<-as.data.frame(res10[2,]) # keep second row of output 

sesoi10<- sesoi_gen
z10<-(res10[,"beta"]-sesoi10)/res10[,"SE"]
p_sesoi10=pt(-z10, df = res10[,"df_Satt"])

t10  <-sapply(res10$df, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.9
res10<-cbind(res10, sesoi=sesoi10, p_sesoi=p_sesoi10, t_Satt_crit=t10, ci_l=res10$beta-t10*res10[,"SE"], ci_u=res10[,"beta"]+t10*res10[,"SE"], 
            coverage=0.9, N=length(lm10$residuals))
rownames(res10)<-paste(rownames(res10),"t_motivation_score.COMBO")
res10

# Teacher outcome 4: teacher paid regularly

y.tr11 <- dat.ts$std_t_funds_regularpay_score
lm11<-lm( formula(paste("y.tr11", "XX_ts", sep="~")),  weights=dat.ts$wt)
res11<-coef_test(lm11, vcov=vcovCR(lm11, cluster=dat.ts$CLUSTER, type="CR2"))
print(res11)

#full results [for appendix]
res11full<-as.data.frame(res11)

#main results without all the covariates [for main body of paper]
res11<-as.data.frame(res11[2,]) # keep second row of output 

sesoi11<- sesoi_gen
z11<-(res11[,"beta"]-sesoi11)/res11[,"SE"]
p_sesoi11=pt(-z11, df = res11[,"df_Satt"])

t11 <-sapply(res11$df, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.9
res11<-cbind(res11, sesoi=sesoi11, p_sesoi=p_sesoi11, t_Satt_crit=t11, ci_l=res11$beta-t11*res11[,"SE"], ci_u=res11[,"beta"]+t11*res11[,"SE"], 
             coverage=0.9, N=length(lm11$residuals))
rownames(res11)<-paste(rownames(res11),"t_funds_regularpay_score")
res11

# Teacher outcome 5: intrinsic motivation 

y.tr12 <- dat.ts$std_t_motivation_intrinsic_score
lm12<-lm( formula(paste("y.tr12", "XX_ts", sep="~")),  weights=dat.ts$wt)
res12<-coef_test(lm12, vcov=vcovCR(lm12, cluster=dat.ts$CLUSTER, type="CR2"))
print(res12)

#full results [for appendix]
res12full<-as.data.frame(res12)

#main results without all the covariates [for main body of paper]
res12<-as.data.frame(res12[2,]) # keep second row of output 

sesoi12<- sesoi_gen
z12<-(res12[,"beta"]-sesoi12)/res12[,"SE"]
p_sesoi12=pt(-z12, df = res12[,"df_Satt"])

t12 <-sapply(res12$df, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.9
res12<-cbind(res12, sesoi=sesoi12, p_sesoi=p_sesoi12, t_Satt_crit=t12, ci_l=res12$beta-t12*res12[,"SE"], ci_u=res12[,"beta"]+t12*res12[,"SE"], 
             coverage=0.9, N=length(lm12$residuals))
rownames(res12)<-paste(rownames(res12),"t_motivation_intrinsic_score")
res12

# Teacher outcome 6: material motivation and satisfaction 

y.tr13 <- dat.ts$std_t_motivation_material_score
lm13<-lm( formula(paste("y.tr13", "XX_ts", sep="~")),  weights=dat.ts$wt)
res13<-coef_test(lm13, vcov=vcovCR(lm13, cluster=dat.ts$CLUSTER, type="CR2"))
print(res13)

#full results [for appendix]
res13full<-as.data.frame(res13)

#main results without all the covariates [for main body of paper]
res13<-as.data.frame(res13[2,]) # keep second row of output 

sesoi13<- sesoi_gen
z13<-(res13[,"beta"]-sesoi13)/res13[,"SE"]
p_sesoi13=pt(-z13, df = res13[,"df_Satt"])

t13 <-sapply(res13$df, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.9
res13<-cbind(res13, sesoi=sesoi13, p_sesoi=p_sesoi13, t_Satt_crit=t13, ci_l=res13$beta-t13*res13[,"SE"], ci_u=res13[,"beta"]+t13*res13[,"SE"], 
             coverage=0.9, N=length(lm13$residuals))
rownames(res13)<-paste(rownames(res13),"t_motivation_material_score")
res13

# combine all the main hh and child results in figure 3 of main paper 
agency_results <- rbind(res7, res8, res9, res11, res6,
                        res4, res5, res10, res12, res13)
print(agency_results) 

agency_for_graph <- data.frame(ATE=agency_results$beta,
                                  lower=agency_results$ci_l,
                                  upper=agency_results$ci_u,
                                  SESOI=agency_results$sesoi,
                                  p_sesoi=agency_results$p_sesoi)
agency_for_graph$p_sesoi[5] <- res6$p_Satt
rownames(agency_for_graph) <- c("CL: classroom supplies",
                                  "TS: combined fund application index",
                                  "TS: classroom supplies",
                                  "TS: teacher paid regularly",
                                  "HH: confidence in local institutions",
                                  "HH: teacher attendance",
                                  "HH: perception of teacher quality",
                                  "TS: combined motivation index",
                                  "TS: intrinsic motivation",
                                  "TS: material motivation and satisfaction")

write.csv(agency_for_graph,
          file="tabs-figs/agency_results.csv",
          row.names = TRUE)

#####################
# VISUAL RESULTS
#####################

dat_agency<-read.csv("tabs-figs/agency_results.csv")

####################
# AGENCY PROBLEMS #
####################

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[1]), lower=c(dat_agency$lower[1]), 
             upper=c(dat_agency$upper[1]))
plot1<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.5, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.5,-0.139,round(d$ATE, 2),0,0.1,0.2,0.3,0.4, 0.5, 0.6, 0.7, 0.8, 0.9), 
                     labels=c("","-0.15","","0","","0.2","","0.4", "", "0.6", "","0.8",""), 
                     limits=c(-0.5,0.9), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[1]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.7, y = 1.5, label = paste0("p-SESOI = ",round(dat_agency$p_sesoi[1],2)), size = 5) + 
  ggtitle("CL: classroom supplies") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.5, 0.92))

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[2]), lower=c(dat_agency$lower[2]), 
             upper=c(dat_agency$upper[2]))
plot2<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.4, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.4,-0.139,0,0.1,0.2,0.3,round(d$ATE, 3), 0.5, 0.6, 0.7, 0.8, 0.9), 
                     labels=c("","-0.15","0","","0.2","",paste0(round(d$ATE, 3)), "","0.6","","0.8",""), 
                     limits=c(-0.4,0.9), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[2]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.7, y = 1.5, label = "p-SESOI = 0.00***", size = 5) + 
  ggtitle("TS: combined fund application index") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.4, 0.9))

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[3]), lower=c(dat_agency$lower[3]), 
             upper=c(dat_agency$upper[3]))
plot3<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.4, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.4,-0.139,0,d$ATE,0.1,0.2,0.3,0.4,0.5, 0.6, 0.7, 0.8, 0.9), 
                     labels=c("","-0.15","0",paste0(round(d$ATE, 2)),"","0.2","","0.4","", "0.6","","0.8",""), 
                     limits=c(-0.4,0.9), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[3]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.7, y = 1.5, label = paste0("p-SESOI = ",round(dat_agency$p_sesoi[3],2),"*"), size = 5) + 
  ggtitle("TS: classroom supplies") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.4, 0.92))

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[4]), lower=c(dat_agency$lower[4]), 
             upper=c(dat_agency$upper[4]))
plot4<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.4, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.4,-0.139,0,0.1,0.2,0.3,0.4,d$ATE, 0.6,0.7, 0.8, 0.9), 
                     labels=c("","-0.15","0","","0.2","","0.4",paste0(round(d$ATE,2)), "","", "0.8", ""), 
                     limits=c(-0.4,0.9), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[4]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.7, y = 1.5, label = "p-SESOI = 0.00***", size = 5) + 
  ggtitle("TS: teacher paid regularly") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.4, 0.92))

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[5]), lower=c(dat_agency$lower[5]), 
             upper=c(dat_agency$upper[5]))
plot5<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.4,0,d$ATE,0.2,0.3,0.4,0.5, 0.6, 0.7, 0.8, 0.9), 
                     labels=c("","",paste0(round(d$ATE,2)),"0.2","","0.4","", "0.6","", "0.8", ""), 
                     limits=c(-0.4,0.9), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n Treatment Effect of Sustainability Model Relative to NGO") +
  theme(
    axis.title.x = element_text(color="black", size=15), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(0), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.7, y = 1.4, label = paste0("p-value = ",round(dat_agency$p_sesoi[5], 2)), size = 5) + 
  ggtitle("HH: confidence in local institutions") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.4, 0.92))

pdf(file="tabs-figs/education_funding.pdf",
    height=12, width=8)
grid.arrange(plot1, plot2, plot3, plot4, plot5,  ncol=1)
dev.off()

# teacher motivation and performance outcomes

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[6]), lower=c(dat_agency$lower[6]), 
             upper=c(dat_agency$upper[6]))
plot1<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.5, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.5,-0.139,0,d$ATE,0.2,0.3,0.4, 0.5, 0.6), 
                     labels=c("","-0.15","0",paste0(round(d$ATE, 2)),"0.2","","0.4", "", "0.6"), 
                     limits=c(-0.5,0.6), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[6]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.5, y = 1.5, label = "p-SESOI = 0.00***", size = 5) + 
  ggtitle("HH: teacher attendance") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.5, 0.62))

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[7]), lower=c(dat_agency$lower[7]), 
             upper=c(dat_agency$upper[7]))
plot2<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.5, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.5,-0.139,-d$ATE,0,0.1,0.2,0.3,0.4,0.5, 0.6), 
                     labels=c("","-0.15",paste(round(d$ATE, 2)),"0","","0.2","","0.4", "","0.6"), 
                     limits=c(-0.5,0.6), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[7]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.5, y = 1.5, label = paste0("p-SESOI = ", round(dat_agency$p_sesoi[7], 2)), size = 5) + 
  ggtitle("HH: perception of teacher quality") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.5, 0.62))

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[8]), lower=c(dat_agency$lower[8]), 
             upper=c(dat_agency$upper[8]))
plot3<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.5, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.5,-0.139,0,d$ATE,0.1,0.2,0.3,0.4,0.5, 0.6), 
                     labels=c("","-0.15","0",paste0(round(d$ATE,2)),"","0.2","","0.4","", "0.6"), 
                     limits=c(-0.5,0.6), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10), 
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[8]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.5, y = 1.5, label = paste0("p-SESOI = ", round(dat_agency$p_sesoi[8],2),"*"), size = 5) + 
  ggtitle("TS: combined motivation index") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.5, 0.62))


d=data.frame(y="", 
             ATE=c(dat_agency$ATE[9]), lower=c(dat_agency$lower[9]), 
             upper=c(dat_agency$upper[9]))
plot4<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.5, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.5,d$ATE,-0.139,0,0.1,0.2,0.3,0.4,0.5, 0.6), 
                     labels=c("","","-0.15","0","","0.2","","0.4","", "0.6"), 
                     limits=c(-0.5,0.6), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n") +
  theme(
    axis.title.x = element_text(color="black", size=10),
    axis.text.x =element_text(size=15), 
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[9]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.5, y = 1.5, label = paste0("p-SESOI = ",round(dat_agency$p_sesoi[9], 2)), size = 5) + 
  ggtitle("TS: intrinsic motivation") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.5, 0.62))

d=data.frame(y="", 
             ATE=c(dat_agency$ATE[10]), lower=c(dat_agency$lower[10]), 
             upper=c(dat_agency$upper[10]))
plot5<- ggplot() + 
  geom_errorbarh(data=d, mapping=aes(y=y, xmin=upper, xmax=lower),
                 height=0.3, size=0.5, color="black") + 
  geom_rect(aes(xmin=-.5, xmax=sesoi_gen, ymin=-0.4, ymax=2), fill = "gray", alpha = .4) +
  geom_point(data=d, mapping=aes(x=ATE, y=y), size=5, shape=21, fill="white") + 
  scale_x_continuous(breaks=c(-0.5,-0.139,0, 0.1,d$ATE,0.3,0.4,0.5, 0.6), 
                     labels=c("","-0.15","0","","0.2","","0.4","", "0.6"), 
                     limits=c(-0.5,0.6), expand = c(0, 0))  + 
  theme_classic() + 
  ylab("")  + xlab("\n Treatment Effect of Sustainability Model Relative to NGO") +
  theme(
    axis.title.x = element_text(color="black", size=15), 
    axis.text.x =element_text(size=15),
    axis.ticks.y = element_blank())  +
  geom_vline(xintercept=c(dat_agency$SESOI[10]), linetype=c("dotted"), color=c("black")) +
  annotate("text", x = 0.5, y = 1.5, label = paste0("p-SESOI = ",round(dat_agency$p_sesoi[10], 2),"**"), size = 5) + 
  ggtitle("TS: material motivation and satisfaction") + theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.title = element_text(size = 15, face = "bold")) + 
  coord_cartesian(xlim = c(-0.5, 0.62))


pdf(file="tabs-figs/teacher_motivation_performance.pdf",
    height=12, width=8)
grid.arrange(plot1, plot2, plot3, plot4, plot5,  ncol=1)
dev.off()

###############################################################################
#### TABLE 2: COMMUNITY LEADERS' LONGER-TERM PERCEPTIONS OF CBE SUSTAINABILITY 
###############################################################################

## Note that this analysis subsets only to CARE communities  

y.tr14<-CARE_cl$phone_sustain_want_score_rev
lm14<-lm( formula(paste("y.tr14", "XX_CARE_cl", sep="~")),  weights=CARE_cl$wt)
res14<-coef_test(lm14, vcov=vcovCR(lm14, cluster=CARE_cl$CLUSTER, type="CR2"))
print(res14)
#full results [for appendix]
res14full<-as.data.frame(res14)

#main results without all the covariates [for main body of paper]
res14<-as.data.frame(res14[2,]) # keep second row of output 

sesoi14<- NA
z7<-(res14[,"beta"]-sesoi14)/res14[,"SE"]
p_sesoi14=pt(-z7, df = res14[,"df_Satt"])
t14  <-sapply(res14$df_Satt, function(d) qt(1-(1-.9)/2, df=d)) #ci=0.90
res14<-cbind(res14, t_Satt_crit=t14, ci_l=res14$beta-t14*res14[,"SE"], ci_u=res14[,"beta"]+t14*res14[,"SE"], 
            coverage=0.9, N=length(lm14$residuals))

rownames(res14)<-paste(rownames(res14),"phone_sustain_want_score_rev")
print(res14)

# indexes tested under non-equivalency hypothesis  

# first index: sustain.index_std

y.tr15<-CARE_cl$sustain.index_std
lm15<-lm( formula(paste("y.tr15", "XX_CARE_cl", sep="~")),  weights=CARE_cl$wt)
res15<-coef_test(lm15, vcov=vcovCR(lm15, cluster=CARE_cl$CLUSTER, type="CR2"))
print(res15)
#full results [for appendix]
res15full<-as.data.frame(res15)

#main results without all the covariates [for main body of paper]
res15<-as.data.frame(res15[2,]) # keep second row of output 

t15  <-sapply(res15$df_Satt, function(d) qt(1-(1-.95)/2, df=d)) #ci=0.95
res15<-cbind(res15, t_Satt_crit=t15, ci_l=res15$beta-t15*res15[,"SE"], ci_u=res15[,"beta"]+t15*res15[,"SE"], 
             coverage=0.95, N=length(lm15$residuals))

rownames(res15)<-paste(rownames(res15),"sustain.index_std")
print(res15)

# second index: phone_sustain_initiative_score_std

y.tr16<-CARE_cl$phone_sustain_initiative_score_std
lm16<-lm( formula(paste("y.tr16", "XX_CARE_cl", sep="~")),  weights=CARE_cl$wt)
res16<-coef_test(lm16, vcov=vcovCR(lm16, cluster=CARE_cl$CLUSTER, type="CR2"))
print(res16)

#full results [for appendix]
res16full<-as.data.frame(res16)

#main results without all the covariates [for main body of paper]
res16<-as.data.frame(res16[2,]) # keep second row of output 

t16  <-sapply(res16$df_Satt, function(d) qt(1-(1-.95)/2, df=d)) #ci=0.95
res16<-cbind(res16, t_Satt_crit=t16, ci_l=res16$beta-t16*res16[,"SE"], ci_u=res16[,"beta"]+t16*res16[,"SE"], 
             coverage=0.95, N=length(lm16$residuals))

rownames(res16)<-paste(rownames(res16),"phone_sustain_initiative_score_std")
print(res16)

# third index: phone_sustain_provisions_score_std

y.tr17<-CARE_cl$phone_sustain_provisions_score_std
lm17<-lm( formula(paste("y.tr17", "XX_CARE_cl", sep="~")),  weights=CARE_cl$wt)
res17<-coef_test(lm17, vcov=vcovCR(lm17, cluster=CARE_cl$CLUSTER, type="CR2"))
print(res17)

#full results [for appendix]
res17full<-as.data.frame(res17)

#main results without all the covariates [for main body of paper]
res17<-as.data.frame(res17[2,]) # keep second row of output 

t17  <-sapply(res17$df_Satt, function(d) qt(1-(1-.95)/2, df=d)) #ci=0.95
res17<-cbind(res17, t_Satt_crit=t17, ci_l=res17$beta-t17*res17[,"SE"], ci_u=res17[,"beta"]+t17*res17[,"SE"], 
             coverage=0.95, N=length(lm17$residuals))

rownames(res17)<-paste(rownames(res17),"phone_sustain_provisions_score_std")
print(res17)

# fourth index: phone_sustain_confidence_score

y.tr18<-CARE_cl$phone_sustain_confidence_score
lm18<-lm( formula(paste("y.tr18", "XX_CARE_cl", sep="~")),  weights=CARE_cl$wt)
res18<-coef_test(lm18, vcov=vcovCR(lm18, cluster=CARE_cl$CLUSTER, type="CR2"))
print(res18)

#full results [for appendix]
res18full<-as.data.frame(res18)

#main results without all the covariates [for main body of paper]
res18<-as.data.frame(res18[2,]) # keep second row of output 

t18  <-sapply(res18$df_Satt, function(d) qt(1-(1-.95)/2, df=d)) #ci=0.95
res18<-cbind(res18, t_Satt_crit=t18, ci_l=res18$beta-t18*res18[,"SE"], ci_u=res18[,"beta"]+t18*res18[,"SE"], 
             coverage=0.95, N=length(lm18$residuals))

rownames(res18)<-paste(rownames(res18),"phone_sustain_confidence_score")
print(res18)

# fifth index: phone_sustain_2018_score

y.tr19<-CARE_cl$phone_sustain_2018_score
lm19<-lm( formula(paste("y.tr19", "XX_CARE_cl", sep="~")),  weights=CARE_cl$wt)
res19<-coef_test(lm19, vcov=vcovCR(lm19, cluster=CARE_cl$CLUSTER, type="CR2"))
print(res19)

#full results [for appendix]
res19full<-as.data.frame(res19)

#main results without all the covariates [for main body of paper]
res19<-as.data.frame(res19[2,]) # keep second row of output 

t19  <-sapply(res19$df_Satt, function(d) qt(1-(1-.95)/2, df=d)) #ci=0.95
res19<-cbind(res19, t_Satt_crit=t19, ci_l=res19$beta-t19*res19[,"SE"], ci_u=res19[,"beta"]+t19*res19[,"SE"], 
             coverage=0.95, N=length(lm19$residuals))

rownames(res19)<-paste(rownames(res19),"phone_sustain_2018_score")
print(res19)

# combining results in Table 2 together

Table2_Output<-rbind(res14, res15, res16, res17, res18, res19)
Table2_sum <- rbind(stat24, stat25, stat26, stat27, stat28, stat29)
Table2_format <- data.frame(Treatment.Effect = round(Table2_Output$beta, 2),
                            Std.Err. = sapply(round(Table2_Output$SE, 2),
                                              function(x) {paste0("(",x,")")}),
                            N = Table2_Output$N,
                            Control.Mean = round(Table2_sum[,"mean"],2),
                            Control.Std.Dev. = round(Table2_sum[,"sd"],2))
rownames(Table2_format) <- rownames(Table2_sum)

Table2_print<-xtable(Table2_format,
       caption="\\label{tab:follow_up}Community Leaders' Longer-term Perceptions of CBE Sustainability")

addtorow <- list()
addtorow$pos <- list(0,1,1)
addtorow$command <- c("{\\bf Equivalency Outcome}  &  &  &  & &  & &\\\\\n",
                      "\\\\\n",
                      "{\\bf Non-Equivalency Outcomes}  &  &  &  & &  & & \\\\\n")
sink(file="tabs-figs/cl_follow_up_sustainability_tomod.tex")
print(Table2_print, 
      add.to.row = addtorow,
      caption.placement = "top",
      hline.after = -1)
sink()




######################################################
######################################################
######################################################
## Appendix
######################################################
######################################################
######################################################

#############################################################################################
### TABLE A2: PAST VIOLENCE
############################################################################################

# Create interaction terms

dat.hh$logsec_sc = log(dat.hh$sec_events)
dat.hh$logsec = (log(dat.hh$sec_events)-mean(log(dat.hh$sec_events)))/sd(log(dat.hh$sec_events))
dat.hh$HAND_logsec = dat.hh$HAND*dat.hh$logsec
dat.hh$HAND_kapisa <- dat.hh$HAND*dat.hh$PROVINCE2 #interaction between Kapisa and treatment variable to account for differential missingness
dat.hh$HAND_parwan <- dat.hh$HAND*dat.hh$PROVINCE1 #interaction between Parwan and treatment variable to account for differential missingness

# aged 8-13 attendance outcome with child cov2 list

subsetviol1<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"ros_attend"]))&(!is.na(dat.hh$wt))
y.trviol1 <- dat.hh[subsetviol1, "ros_attend"]
XXviol1<-as.matrix(cbind(dat.hh[subsetviol1, c("TREAT", "HAND", "logsec", "HAND_logsec", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh[subsetviol1, cov2.child], dm)))
lmviol1<-lm( formula(paste("y.trviol1", "XXviol1", sep="~")),  weights=dat.hh$wt[subsetviol1])
resviol1<-coef_test(lmviol1, vcov=vcovCR(lmviol1, cluster=dat.hh$CLUSTER[subsetviol1], type="CR2"))
print(resviol1)

#for supplementary appendix
resviol1_full<-as.data.frame(resviol1)

resviol1<-as.data.frame(resviol1[2:4,]) # keep second row of output 

# aged 8-13 std_mathread with child cov2 list

subsetviol2<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"std_mathread"]))&(!is.na(dat.hh$wt))
y.trviol2 <- dat.hh[subsetviol2, "std_mathread"]
XXviol2<-as.matrix(cbind(dat.hh[subsetviol2, c("TREAT", "HAND", "logsec", "HAND_logsec", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh[subsetviol2, cov2.child], dm)))
lmviol2<-lm( formula(paste("y.trviol2", "XXviol2", sep="~")),  weights=dat.hh$wt[subsetviol2])
resviol2<-coef_test(lmviol2, vcov=vcovCR(lmviol2, cluster=dat.hh$CLUSTER[subsetviol2], type="CR2"))
print(resviol2)

#for supplementary appendix
resviol2_full<-as.data.frame(resviol2)

resviol2<-as.data.frame(resviol2[2:4,]) # keep second row of output 

# household, satisfaction_access_score

subsetviol3<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"satisfaction_access_score"]))&(!is.na(dat.hh$wt))
y.tmpviol3<-dat.hh[subsetviol3, "satisfaction_access_score"]
wms.viol3<-wtd.mean.sd(y.tmpviol3[dat.hh$HAND[subsetviol3]==0&dat.hh$TREAT[subsetviol3]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subsetviol3])
y.trviol3<-(dat.hh[subsetviol3, "satisfaction_access_score"]-wms.viol3$mean)/wms.viol3$sd
XXviol3<-as.matrix(cbind(dat.hh[subsetviol3, c("TREAT", "HAND", "logsec", "HAND_logsec", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh[subsetviol3, cov2.hh], dm)))
lmviol3<-lm( formula(paste("y.trviol3", "XXviol3", sep="~")),  weights=dat.hh$wt[subsetviol3])
resviol3<-coef_test(lmviol3, vcov=vcovCR(lmviol3, cluster=dat.hh$CLUSTER[subsetviol3], type="CR2"))
print(resviol3)

#for supplementary appendix
resviol3_full<-as.data.frame(resviol3)

resviol3<-as.data.frame(resviol3[2:4,]) # keep second to fourth row of output 


violence_out <- t(
  cbind(
    cbind(paste(c(round(resviol1$beta, 2),length(lmviol1$residuals))),c(sapply(resviol1$SE, addParens, 2),"")),
    cbind(paste(c(round(resviol2$beta, 2),length(lmviol2$residuals))),c(sapply(resviol2$SE, addParens, 2),"")),
    cbind(paste(c(round(resviol3$beta, 2),length(lmviol3$residuals))),c(sapply(resviol3$SE, addParens, 2),""))
  )
)

violence_print <- data.frame(
  Outcome = c("Child attendance","",
              "Child test score","",
              "HH satisfaction",""),
  Treatment = violence_out[,1],
  Log.sec.events = violence_out[,2],
  Treatment.X.Log.sec.events = violence_out[,3],
  N=violence_out[,4])

sink(file="tabs-figs/hh_child_violence.tex")
print(xtable(violence_print,
             caption="\\label{tab:violence_interacted_results} Interaction Effects Regressions With 2003-2013 Security Events with Main Child and Household Outcomes"),
      include.rownames=F,
      caption.placement = "top",
      hline.after = c(-1,0))
sink()


anso <- read.dta13("anso-totals.dta")
anso_alse <- na.omit(read.csv("anso-events-alse.csv"))

pdf(file="tabs-figs/violence.pdf", height=6, width=8)
hist(log10(anso$sec_events), axes=F,
     xlab="Security incidents (log10 scaled)",
     ylab="",
     main="")
abline(v=log10(anso_alse$sec_incidents))
axis(1, 
     at=c(0,1,2,3,4),
     labels=c(10^0,10^1,10^2,10^3,10^4))
dev.off()



##############################################################################
### TABLE A6 : REALIZED SAMPLE SIZES
##############################################################################


sink(file="tabs-figs/sample-sizes.txt")
apply(table(within_hh_dat$CLUSTER, within_hh_dat$HAND),
      2,
      function(x)sum(x>0))

apply(table(within_hh_dat$VUID, within_hh_dat$HAND),
      2,
      function(x)sum(x>0))

table(within_hh_dat$HAND)
table(children_dat$HAND)
table(dat.cl$HAND)
table(dat.ts$HAND)
sink()

##############################################################################
### TABLE A7 : COVARIATE BALANCE PLACEBO REGRESSIONS
##############################################################################

# this is a regression function that runs for each of the individual covariate
runregs<-function(y, covars=NA, data=dat.hh, subset=(data$ros_age611==1)
                  , cluster=data$CLUSTER, sesoi=NA , saverows=c(3)
                  , standardize=FALSE, ci=.95, interaction.dummies=NULL){
  subset2<-(is.na(eval(parse(text=subset)))==FALSE)&
    eval(parse(text=subset))&(!is.na(data[,y]))&(!is.na(data$wt))
  binary.outcome<-(length(table(data[subset2, y]))==2)&
    (min(data[subset2, y])==0)&(max(data[subset2, y])==1)
  if(standardize==TRUE & binary.outcome==FALSE){
    y.tmp<-data[subset2, y]
    wms<-wtd.mean.sd(y.tmp[data$HAND[subset2]==0&data$TREAT[subset2]==1], data$wt[data$HAND==0&data$TREAT==1&subset2])
    y.tr<-(data[subset2, y]-wms$mean)/wms$sd
  }else{
    y.tr<-data[subset2, y]
  }
  if(is.na((covars)[1])==FALSE){
    XX<-as.matrix(cbind(data[subset2, c("TREAT", "HAND")], sapply(data[subset2, covars], dm)))
  }else{
    XX<-as.matrix(data[subset2, c("TREAT", "HAND")])
  }
  lm0<-lm( formula(paste("y.tr", "XX", sep="~")),  weights=data$wt[subset2])
  res<-coef_test(lm0, vcov=vcovCR(lm0, cluster=cluster[subset2], type="CR2"))
  print(res)
  res<-as.data.frame(res[saverows,])
  if(!is.na(sesoi)){
    z<-(res[,"beta"]-sesoi)/res[,"SE"]
    p_sesoi=pt(-z, df = res[,"df"])
  }else{
    p_sesoi<-NA
  }
  t  <-sapply(res$df, function(d) qt(1-(1-ci)/2, df=d))
  res<-cbind(res, sesoi=sesoi, p_sesoi=p_sesoi, t_Satt_crit=t, ci_l=res$beta-t*res[,"SE"], ci_u=res[,"beta"]+t*res[,"SE"], coverage=ci, N=length(lm0$residuals), standardized=standardize, binary=binary.outcome)
  rownames(res)<-paste(rownames(res), y, subset, sep="_")
  res
}

placebo.cov<-lapply(list(NA)
                    , function(cv) 
                      t(mapply(function(v, s) 
                        runregs(v, covars=NA, subset="(dat.hh$TREAT==1&dat.hh$within.hh.id==1)", saverows=2, 
                                sesoi=s, ci=.95 , standardize=TRUE), 
                        v=cov2.child, s=NA))
)



Balance_Table <- data.frame(Placebo.Effect = round(unlist(placebo.cov[[1]][,"beta"]),2),
                            SE = sapply(round(unlist(placebo.cov[[1]][,"SE"]),2),
                                        function(x)paste0("(",x,")")),
                            Unadj.p.value=round(unlist(placebo.cov[[1]][,"p_Satt"]), 2))


Balance_print <- xtable(Balance_Table,
       caption="\\label{tab:cov_balance} Covariate Balance Placebo Regressions")

addtorow <- list()
addtorow$pos <- list(0,3,3, 36, 36)
addtorow$command <- c("{\\bf Child Covariates}  &  &  &  & &  & &\\\\\n",
                      "\\\\\n",
                      "{\\bf Household Covariates}  &  &  &  & &  & & \\\\\n",
                      "\\\\\n",
                      "{\\bf Province Indicators}  &  &  &  & &  & & \\\\\n")
sink(file="tabs-figs/covariate_balance_tomod.tex")
print(Balance_print, 
      add.to.row = addtorow,
      caption.placement = "top")
sink()


##############################################################################
### TABLE A8: PLACEBO TEST OF DIFFERETIAL MISSINGNESS BETWEEN TREATMENT 
### AND CONTROL CONDITIONS
##############################################################################

#missing teacher attendance 
dat.hh$teacher_attend_score_na <- ifelse(is.na(dat.hh$teacher_attend_score), 1, 0) #dummy for missing teacher attend score
subset1<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"teacher_attend_score_na"]))&(!is.na(dat.hh$wt))

# teacher_attend_score_na is a binary outcome:
y.tr1<-dat.hh[subset1, "teacher_attend_score_na"]

# covariates
XX1<-as.matrix(dat.hh[subset1, c("TREAT", "HAND")])

lm1<-lm( formula(paste("y.tr1", "XX1", sep="~")),  weights=dat.hh$wt[subset1])
res1<-coef_test(lm1, vcov=vcovCR(lm1, cluster=dat.hh$CLUSTER[subset1], type="CR2"))
print(res1)
res1<-as.data.frame(res1[2,]) # keep second row of output 

# add in t_Satt_citical
t1 <-sapply(res1$df, function(d) qt(1-(1-0.95)/2, df=d)) # ci= 0.95

# final set of results for teacher_attend_score_na
res1<-cbind(res1, t_Satt_crit=t1, ci_l=res1$beta-t1*res1[,"SE"],
            ci_u=res1[,"beta"]+t1*res1[,"SE"],
            coverage=0.95, N=length(lm1$residuals))
rownames(res1)<-paste(rownames(res1), 'teacher_attend_score_na')
res1

#number of children tested in household

subset2<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"num_tested_children"]))&(!is.na(dat.hh$wt))

# num_tested_children is not a binary outcome:
y.tr2<-dat.hh[subset2, "num_tested_children"]

# covariates
XX2<-as.matrix(dat.hh[subset2, c("TREAT", "HAND")])

lm2<-lm( formula(paste("y.tr2", "XX2", sep="~")),  weights=dat.hh$wt[subset2])
res2<-coef_test(lm2, vcov=vcovCR(lm2, cluster=dat.hh$CLUSTER[subset2], type="CR2"))
print(res2)
res2<-as.data.frame(res2[2,]) # keep second row of output 

# add in t_Satt_citical
t2 <-sapply(res2$df, function(d) qt(1-(1-0.95)/2, df=d)) # ci= 0.95

# final set of results for teacher_attend_score_na
res2<-cbind(res2, t_Satt_crit=t2, ci_l=res2$beta-t2*res2[,"SE"],
            ci_u=res2[,"beta"]+t2*res2[,"SE"],
            coverage=0.95, N=length(lm2$residuals))
rownames(res2)<-paste(rownames(res2), 'num_tested_children')
res2

#number of children attending in household

subset3<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"num_attend"]))&(!is.na(dat.hh$wt))

# num_attend is not a binary outcome:
y.tr3<-dat.hh[subset3, "num_attend"]

# covariates
XX3<-as.matrix(dat.hh[subset3, c("TREAT", "HAND")])

lm3<-lm( formula(paste("y.tr3", "XX3", sep="~")),  weights=dat.hh$wt[subset3])
res3<-coef_test(lm3, vcov=vcovCR(lm3, cluster=dat.hh$CLUSTER[subset3], type="CR2"))
print(res3)
res3<-as.data.frame(res3[2,]) # keep second row of output 

# add in t_Satt_citical
t3 <-sapply(res3$df, function(d) qt(1-(1-0.95)/2, df=d)) # ci= 0.95

# final set of results for teacher_attend_score_na
res3<-cbind(res3, t_Satt_crit=t3, ci_l=res3$beta-t3*res3[,"SE"],
            ci_u=res3[,"beta"]+t3*res3[,"SE"],
            coverage=0.95, N=length(lm3$residuals))
rownames(res3)<-paste(rownames(res3), 'num_attend')
res3

Attrition_Output<-rbind(res1, res2, res3)
Attrition_format <- data.frame(Treatment.Effect = round(Attrition_Output$beta, 2),
                            Std.Err. = sapply(round(Attrition_Output$SE, 2),
                                              function(x) {paste0("(",x,")")}),
                            p.value = round(Attrition_Output$p_Satt,2),
                            N = Attrition_Output$N)


rownames(Attrition_format) <- c("Missing teacher attendance outcome",
                                "Number of children tested in household",
                                "Number of children attending in household")

Attrition_print<-xtable(Attrition_format,
                     caption="\\label{tab:missing} Placebo Test of Differential Missingness Between Treatment and Control Conditions")

sink(file="tabs-figs/missingness_test_tomod.tex")
print(Attrition_print, caption.placement = "top")
sink()


##############################################################################
### TABLE A10: HETEROGENEOUS TREATMENT EFFECTS BY GENDER AND ETHNIC STATUS
##############################################################################

# We estimate no-intercept interacted models, which
# allows us to obtain estimates of the group means and group-specific
# treatment effects.
# We then use Wald tests to test for significant differences in the group
# specific treatment effect estimates.

## FIRST BY GENDER

# Heterogeneity Test for Boys and Girls' Attendance

dat.hh$male   <- 1-dat.hh$ros_girl
dat.hh$female <- dat.hh$ros_girl
dat.hh$hh_eth_NO <- 1-(dat.hh$hh_eth_hazara+dat.hh$hh_eth_pashtun+dat.hh$hh_eth_tajik)

subset.het1<-(is.na(eval(parse(text='(dat.hh$ros_age0813==TRUE&dat.hh$TREAT==1&dat.hh$hh_eth_NO==0)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1&dat.hh$hh_eth_NO==0)'))&(!is.na(dat.hh[,"ros_attend"]))&(!is.na(dat.hh$wt))

y.tr.het1<-dat.hh[subset.het1, "ros_attend"]

cov2.hh.int<-c(cov1.hh, "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read"
               , "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government",
               "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000", 
               "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs", 
               "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children", 
               "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

covars<-cov2.hh.int[-c(2:4)]
interaction.dummies1<-c("female","male")

tmp.het1<-cbind(dat.hh[,interaction.dummies1]
                , sapply(dat.hh[,interaction.dummies1]
                         ,function(x) x*dat.hh$HAND))

colnames(tmp.het1)[3:4] <- c("femXhand","malXhand")

XX.het1<-as.matrix(cbind(tmp.het1[subset.het1, ]
                         , sapply(dat.hh[subset.het1, covars], dm)))

lm.het1<-lm(formula(paste("y.tr.het1", "XX.het1", sep="~0+"))
            , weights=dat.hh$wt[subset.het1])

res.het1<-coef_test(lm.het1, vcov=vcovCR(lm.het1, cluster=dat.hh$CLUSTER[subset.het1], type="CR2"))

#full results [for appendix]
res.het1.full<-as.data.frame(res.het1)

#main results without all the covariates [for main appendix]
res.het1<-as.data.frame(res.het1[c(1:4),])
print(summary(lm.het1))
sesoi.het1<-NA
p_sesoi.het1<-NA
t.het1  <- sapply(res.het1$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het1<- length(interaction.dummies1)
constraint.mat.het1<- matrix(rep(0, dim(XX.het1)[2]*(k.dummy.het1-1)) , ncol=dim(XX.het1)[2])
for( i in 1:(k.dummy.het1-1) ) {
  print(sum(subset.het1))
  print(k.dummy.het1)
  print(paste("dim constraint.mat.het1=", dim(constraint.mat.het1)))
  constraint.mat.het1[i, i+k.dummy.het1  ] <-  1
  constraint.mat.het1[i, i+k.dummy.het1+1] <- -1
}
print(constraint.mat.het1)
wald.het1 <- Wald_test(lm.het1, constraint.mat.het1, cluster=dat.hh$CLUSTER[subset.het1] , vcov="CR2")
v.cov1<- vcovCR(lm.het1, cluster=dat.hh$CLUSTER[subset.het1],type="CR2" )
point.est1  <-as.vector(constraint.mat.het1%*%as.vector(coef(lm.het1)))
v.point.est1<- (constraint.mat.het1%*%v.cov1%*%t(constraint.mat.het1))
test.stat1<-point.est1%*%solve(v.point.est1)%*%point.est1
pchisq(test.stat1, df=2, lower.tail=FALSE)

res.het.bg.attend <- cbind(res.het1, wald.het1, pchisq(test.stat1, df=2, lower.tail=FALSE))

# Ex post power

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov1[3:4,3:4]))
min_det_diff_90

# Heterogeneity Test for Boys and Girls' Math and Reading Scores

subset.het2<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1&dat.hh$hh_eth_NO==0)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1&dat.hh$hh_eth_NO==0)'))&(!is.na(dat.hh[,"std_mathread"]))&(!is.na(dat.hh$wt))

y.tr.het2<-dat.hh[subset.het2, "std_mathread"]

XX.het2<-as.matrix(cbind(tmp.het1[subset.het2, ]
                         , sapply(dat.hh[subset.het2, cov2.hh.int[-c(2:4)]], dm)))

lm.het2<-lm(formula(paste("y.tr.het2", "XX.het2", sep="~0+"))
            , weights=dat.hh$wt[subset.het2])

res.het2<-coef_test(lm.het2, vcov=vcovCR(lm.het2, cluster=dat.hh$CLUSTER[subset.het2], type="CR2"))

#full results [for supplementary appendix]
res.het2.full<-as.data.frame(res.het2)

#main results without all the covariates [for main appendix]
res.het2<-as.data.frame(res.het2[c(1:4),])
print(summary(lm.het2))

sesoi.het2<-NA
p_sesoi.het2<-NA
t.het2  <- sapply(res.het2$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het2<- length(c("female","male"))
constraint.mat.het2<- matrix(rep(0, dim(XX.het2)[2]*(k.dummy.het2-1)) , ncol=dim(XX.het2)[2])
for( i in 1:(k.dummy.het2-1) ) {
  print(sum(subset.het2))
  print(k.dummy.het2)
  print(paste("dim constraint.mat.het1=", dim(constraint.mat.het2)))
  constraint.mat.het2[i, i+k.dummy.het2  ] <-  1
  constraint.mat.het2[i, i+k.dummy.het2+1] <- -1
}
print(constraint.mat.het2)
wald.het2 <- Wald_test(lm.het2, constraint.mat.het2, cluster=dat.hh$CLUSTER[subset.het2] , vcov="CR2")

v.cov2<- vcovCR(lm.het2, cluster=dat.hh$CLUSTER[subset.het2],type="CR2" )
point.est2  <-as.vector(constraint.mat.het1%*%as.vector(coef(lm.het2)))
v.point.est2<- (constraint.mat.het1%*%v.cov2%*%t(constraint.mat.het1))
test.stat2<-point.est2%*%solve(v.point.est2)%*%point.est2
pchisq(test.stat2, df=2, lower.tail=FALSE)

res.het.bg.test <- cbind(res.het2, wald.het2, pchisq(test.stat2, df=2, lower.tail=FALSE))


# Ex post power

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov2[3:4,3:4]))
min_det_diff_90

## SECOND BY WHETHER HOUSEHOLD IS PART OF THE ETHNIC MAJORITY OR MINORITY

# Heterogeneity Test for Ethnic Majorities' and Minorities' Attendance
dat.hh$ones            <-rep(1,dim(dat.hh)[1])

subset.het3<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"ros_attend"]))&(!is.na(dat.hh$wt))

y.tr.het3<-dat.hh[subset.het3, "ros_attend"]

covars<-cov2.hh.int[-c(2:4)]
interaction.dummies3<-c("majority_eth", "minority_eth")

tmp.het3<-cbind(dat.hh[interaction.dummies3]
                , sapply(dat.hh[,interaction.dummies3]
                         ,function(x) x*dat.hh$HAND))
colnames(tmp.het3)[3:4] <- c("majXhand","minXhand")

XX.het3<-as.matrix(cbind(tmp.het3[subset.het3, ]
                         , sapply(dat.hh[subset.het3, covars], dm)))

lm.het3<-lm(formula(paste("y.tr.het3", "XX.het3", sep="~0+"))
            , weights=dat.hh$wt[subset.het3])

res.het3<-coef_test(lm.het3, vcov=vcovCR(lm.het3, cluster=dat.hh$CLUSTER[subset.het3], type="CR2"))

#full results [for supplementary appendix]
res.het3.full<-as.data.frame(res.het3)

#main results without all the covariates [for main appendix]
res.het3<-as.data.frame(res.het3[c(1:4),])
print(summary(lm.het3))
sesoi.het3<-NA
p_sesoi.het3<-NA
t.het3  <- sapply(res.het3$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het3<- length(interaction.dummies3)
constraint.mat.het3<- matrix(rep(0, dim(XX.het3)[2]*(k.dummy.het3-1)) , ncol=dim(XX.het3)[2])
for( i in 1:(k.dummy.het3-1) ) {
  print(sum(subset.het3))
  print(k.dummy.het3)
  print(paste("dim constraint.mat.het3=", dim(constraint.mat.het3)))
  constraint.mat.het3[i, i+k.dummy.het3  ] <-  1
  constraint.mat.het3[i, i+k.dummy.het3+1] <- -1
}
print(constraint.mat.het3)
wald.het3 <- Wald_test(lm.het3, constraint.mat.het3, cluster=dat.hh$CLUSTER[subset.het3] , vcov="CR2")
v.cov3<- vcovCR(lm.het3, cluster=dat.hh$CLUSTER[subset.het3],type="CR2" )
point.est3  <-as.vector(constraint.mat.het3%*%as.vector(coef(lm.het3)))
v.point.est3<- (constraint.mat.het3%*%v.cov3%*%t(constraint.mat.het3))
test.stat3<-point.est3%*%solve(v.point.est3)%*%point.est3
pchisq(test.stat3, df=2, lower.tail=FALSE)

res.het.maj.attend <- cbind(res.het3, wald.het3, pchisq(test.stat3, df=2, lower.tail=FALSE))

# Ex post power

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov3[3:4,3:4]))
min_det_diff_90

# Heterogeneity Test for Ethnic Majorities' and Minorities' Math and Reading Scores

subset.het4<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"std_mathread"]))&(!is.na(dat.hh$wt))

y.tr.het4<-dat.hh[subset.het4, "std_mathread"]

XX.het4<-as.matrix(cbind(tmp.het3[subset.het4, ]
                         , sapply(dat.hh[subset.het4, cov2.hh.int[-c(2:4)]], dm)))

lm.het4<-lm(formula(paste("y.tr.het4", "XX.het4", sep="~0+"))
            , weights=dat.hh$wt[subset.het4])

res.het4<-coef_test(lm.het4, vcov=vcovCR(lm.het4, cluster=dat.hh$CLUSTER[subset.het4], type="CR2"))

#full results [for supplementary appendix]
res.het4.full<-as.data.frame(res.het4)

#main results without all the covariates [for main appendix]
res.het4<-as.data.frame(res.het4[c(1:4),])
print(summary(lm.het4))

sesoi.het4<-NA
p_sesoi.het4<-NA
t.het4  <- sapply(res.het4$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het4<- length(interaction.dummies3)
constraint.mat.het4<- matrix(rep(0, dim(XX.het4)[2]*(k.dummy.het4-1)) , ncol=dim(XX.het3)[2])
for( i in 1:(k.dummy.het4-1) ) {
  print(sum(subset.het4))
  print(k.dummy.het4)
  print(paste("dim constraint.mat.het4=", dim(constraint.mat.het4)))
  constraint.mat.het4[i, i+k.dummy.het4  ] <-  1
  constraint.mat.het4[i, i+k.dummy.het4+1] <- -1
}
print(constraint.mat.het4)
wald.het4 <- Wald_test(lm.het4, constraint.mat.het4, cluster=dat.hh$CLUSTER[subset.het4] , vcov="CR2")
v.cov4<- vcovCR(lm.het4, cluster=dat.hh$CLUSTER[subset.het4],type="CR2" )
point.est4  <-as.vector(constraint.mat.het4%*%as.vector(coef(lm.het4)))
v.point.est4<- (constraint.mat.het4%*%v.cov4%*%t(constraint.mat.het4))
test.stat4<-point.est4%*%solve(v.point.est4)%*%point.est4
pchisq(test.stat4, df=2, lower.tail=FALSE)

res.het.maj.test <- cbind(res.het4, wald.het4, pchisq(test.stat4, df=2, lower.tail=FALSE))

# Ex post power

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov4[3:4,3:4]))
min_det_diff_90

# Heterogeneity Test for Ethnic Majorities' and Minorities' Household Satisfaction

subset.het4b<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"satisfaction_access_score"]))&(!is.na(dat.hh$wt))

y.temp.het4b<- dat.hh[subset.het4b, "satisfaction_access_score"]
wms.het4b<-wtd.mean.sd(y.temp.het4b[dat.hh$HAND[subset.het4b]==0&dat.hh$TREAT[subset.het4b]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subset.het4b])
y.tr.het4b<-(y.temp.het4b-wms.het4b$mean)/wms.het4b$sd

XX.het4b<-as.matrix(cbind(tmp.het3[subset.het4b, ]
                         , sapply(dat.hh[subset.het4b, cov2.hh.int[-c(2:4)]], dm)))

lm.het4b<-lm(formula(paste("y.tr.het4b", "XX.het4b", sep="~0+"))
            , weights=dat.hh$wt[subset.het4b])

res.het4b<-coef_test(lm.het4b, vcov=vcovCR(lm.het4b, cluster=dat.hh$CLUSTER[subset.het4b], type="CR2"))

#full results [for supplementary appendix]
res.het4b.full<-as.data.frame(res.het4b)

#main results without all the covariates [for main appendix]
res.het4b<-as.data.frame(res.het4b[c(1:4),])
print(summary(lm.het4b))

sesoi.het4b<-NA
p_sesoi.het4b<-NA
t.het4b  <- sapply(res.het4b$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het4b<- length(interaction.dummies3)
constraint.mat.het4b<- matrix(rep(0, dim(XX.het4b)[2]*(k.dummy.het4b-1)) , ncol=dim(XX.het3)[2])
for( i in 1:(k.dummy.het4b-1) ) {
  print(sum(subset.het4b))
  print(k.dummy.het4b)
  print(paste("dim constraint.mat.het4b=", dim(constraint.mat.het4b)))
  constraint.mat.het4b[i, i+k.dummy.het4b  ] <-  1
  constraint.mat.het4b[i, i+k.dummy.het4b+1] <- -1
}
print(constraint.mat.het4b)
wald.het4b <- Wald_test(lm.het4b, constraint.mat.het4b, cluster=dat.hh$CLUSTER[subset.het4b] , vcov="CR2")
v.cov4b<- vcovCR(lm.het4b, cluster=dat.hh$CLUSTER[subset.het4b],type="CR2" )
point.est4b  <-as.vector(constraint.mat.het4b%*%as.vector(coef(lm.het4b)))
v.point.est4b<- (constraint.mat.het4b%*%v.cov4b%*%t(constraint.mat.het4b))
test.stat4b<-point.est4b%*%solve(v.point.est4b)%*%point.est4b
pchisq(test.stat4b, df=2, lower.tail=FALSE)

res.het.maj.sat <- cbind(res.het4b, wald.het4b, pchisq(test.stat4b, df=2, lower.tail=FALSE))

# Ex post power

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov4b[3:4,3:4]))
min_det_diff_90

## BY WHETHER HOUSEHOLD IS PART OF THE ETHNIC GROUP OF COMMUNITY LEADER

# Heterogeneity Test for Sharing or Differing from Community Leaders' Ethnicity, Attendance

subset.het5<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"ros_attend"]))&(!is.na(dat.hh$wt))

y.tr.het5<-dat.hh[subset.het5, "ros_attend"]

tmp.het5<-cbind(dat.hh[,c("same_eth_cl", "diff_eth_cl")]
                , sapply(dat.hh[,c("same_eth_cl", "diff_eth_cl")]
                         ,function(x) x*dat.hh$HAND))

colnames(tmp.het5)[3:4] <- c("sameXhand","diffXhand")

XX.het5<-as.matrix(cbind(tmp.het5[subset.het5, ]
                         , sapply(dat.hh[subset.het5, cov2.hh.int[-c(2:4)]], dm)))

lm.het5<-lm(formula(paste("y.tr.het5", "XX.het5", sep="~0+"))
            , weights=dat.hh$wt[subset.het5])

res.het5<-coef_test(lm.het5, vcov=vcovCR(lm.het5, cluster=dat.hh$CLUSTER[subset.het5], type="CR2"))

#full results [for supplementary appendix]
res.het5.full<-as.data.frame(res.het5)

#main results without all the covariates [for main appendix]
res.het5<-as.data.frame(res.het5[c(1:4),])
print(summary(lm.het5))
sesoi.het5<-NA
p_sesoi.het5<-NA
t.het5  <- sapply(res.het5$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het5<- length(c("same_eth_cl", "diff_eth_cl"))
constraint.mat.het5<- matrix(rep(0, dim(XX.het5)[2]*(k.dummy.het5-1)) , ncol=dim(XX.het5)[2])
for( i in 1:(k.dummy.het5-1) ) {
  print(sum(subset.het5))
  print(k.dummy.het5)
  print(paste("dim constraint.mat.het5=", dim(constraint.mat.het5)))
  constraint.mat.het5[i, i+k.dummy.het5  ] <-  1
  constraint.mat.het5[i, i+k.dummy.het5+1] <- -1
}
print(constraint.mat.het5)
wald.het5 <- Wald_test(lm.het5, constraint.mat.het5, cluster=dat.hh$CLUSTER[subset.het5] , vcov="CR2")
v.cov5<- vcovCR(lm.het5, cluster=dat.hh$CLUSTER[subset.het5],type="CR2" )
point.est5  <-as.vector(constraint.mat.het5%*%as.vector(coef(lm.het5)))
v.point.est5<- (constraint.mat.het5%*%v.cov5%*%t(constraint.mat.het5))
test.stat5<-point.est5%*%solve(v.point.est5)%*%point.est5
pchisq(test.stat5, df=2, lower.tail=FALSE)

res.het.cleth.attend <- cbind(res.het5, wald.het5, pchisq(test.stat5, df=2, lower.tail=FALSE))

# Ex post power

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov5[3:4,3:4]))
min_det_diff_90

# Heterogeneity Test for Sharing or Differing from Community Leaders' Ethnicity, Math and Reading Scores

subset.het6<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"std_mathread"]))&(!is.na(dat.hh$wt))

y.tr.het6<-dat.hh[subset.het6, "std_mathread"]

XX.het6<-as.matrix(cbind(tmp.het5[subset.het6, ]
                         , sapply(dat.hh[subset.het6, cov2.hh.int[-c(2:4)]], dm)))

lm.het6<-lm(formula(paste("y.tr.het6", "XX.het6", sep="~0+"))
            , weights=dat.hh$wt[subset.het6])

res.het6<-coef_test(lm.het6, vcov=vcovCR(lm.het6, cluster=dat.hh$CLUSTER[subset.het6], type="CR2"))

#full results [for supplementary appendix]
res.het6.full<-as.data.frame(res.het6)

#main results without all the covariates [for main appendix]
res.het6<-as.data.frame(res.het6[c(1:4),])
print(summary(lm.het6))
sesoi.het6<-NA
p_sesoi.het6<-NA
t.het6  <- sapply(res.het6$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het6<- length(c("same_eth_cl", "diff_eth_cl"))
constraint.mat.het6<- matrix(rep(0, dim(XX.het6)[2]*(k.dummy.het6-1)) , ncol=dim(XX.het6)[2])
for( i in 1:(k.dummy.het6-1) ) {
  print(sum(subset.het5))
  print(k.dummy.het6)
  print(paste("dim constraint.mat.het6=", dim(constraint.mat.het6)))
  constraint.mat.het6[i, i+k.dummy.het6  ] <-  1
  constraint.mat.het6[i, i+k.dummy.het6+1] <- -1
}
print(constraint.mat.het6)
wald.het6 <- Wald_test(lm.het6, constraint.mat.het6, cluster=dat.hh$CLUSTER[subset.het6] , vcov="CR2")

v.cov6<- vcovCR(lm.het6, cluster=dat.hh$CLUSTER[subset.het6],type="CR2" )
point.est6  <-as.vector(constraint.mat.het6%*%as.vector(coef(lm.het6)))
v.point.est6<- (constraint.mat.het6%*%v.cov6%*%t(constraint.mat.het6))
test.stat6<-point.est6%*%solve(v.point.est6)%*%point.est6
pchisq(test.stat6, df=2, lower.tail=FALSE)

res.het.cleth.test <- cbind(res.het6, wald.het6, pchisq(test.stat6, df=2, lower.tail=FALSE))

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov6[3:4,3:4]))
min_det_diff_90

# Heterogeneity Test for Sharing or Differing from Community Leaders' Ethnicity, Household Satisfaction

subset.het6b<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"satisfaction_access_score"]))&(!is.na(dat.hh$wt))

y.temp.het6b<- dat.hh[subset.het6b, "satisfaction_access_score"]
wms.het6b<-wtd.mean.sd(y.temp.het6b[dat.hh$HAND[subset.het6b]==0&dat.hh$TREAT[subset.het6b]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subset.het6b])
y.tr.het6b<-(y.temp.het4b-wms.het6b$mean)/wms.het6b$sd

XX.het6b<-as.matrix(cbind(tmp.het5[subset.het6b, ]
                         , sapply(dat.hh[subset.het6b, cov2.hh.int[-c(2:4)]], dm)))

lm.het6b<-lm(formula(paste("y.tr.het6b", "XX.het6b", sep="~0+"))
            , weights=dat.hh$wt[subset.het6b])

res.het6b<-coef_test(lm.het6b, vcov=vcovCR(lm.het6b, cluster=dat.hh$CLUSTER[subset.het6b], type="CR2"))

#full results [for supplementary appendix]
res.het6b.full<-as.data.frame(res.het6b)

#main results without all the covariates [for main appendix]
res.het6b<-as.data.frame(res.het6b[c(1:4),])
print(summary(lm.het6b))
sesoi.het6b<-NA
p_sesoi.het6b<-NA
t.het6b  <- sapply(res.het6b$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het6b<- length(c("same_eth_cl", "diff_eth_cl"))
constraint.mat.het6b<- matrix(rep(0, dim(XX.het6b)[2]*(k.dummy.het6b-1)) , ncol=dim(XX.het6b)[2])
for( i in 1:(k.dummy.het6b-1) ) {
  print(sum(subset.het6b))
  print(k.dummy.het6b)
  print(paste("dim constraint.mat.het6b=", dim(constraint.mat.het6b)))
  constraint.mat.het6b[i, i+k.dummy.het6b  ] <-  1
  constraint.mat.het6b[i, i+k.dummy.het6b+1] <- -1
}
print(constraint.mat.het6b)
wald.het6b <- Wald_test(lm.het6b, constraint.mat.het6b, cluster=dat.hh$CLUSTER[subset.het6b] , vcov="CR2")

v.cov6b<- vcovCR(lm.het6b, cluster=dat.hh$CLUSTER[subset.het6b],type="CR2" )
point.est6b  <-as.vector(constraint.mat.het6b%*%as.vector(coef(lm.het6b)))
v.point.est6b<- (constraint.mat.het6b%*%v.cov6b%*%t(constraint.mat.het6b))
test.stat6b<-point.est6b%*%solve(v.point.est6b)%*%point.est6b
pchisq(test.stat6b, df=2, lower.tail=FALSE)

res.het.cleth.sat <- cbind(res.het6b, wald.het6b, pchisq(test.stat6b, df=2, lower.tail=FALSE))

min_det_diff_90 <- qnorm(.95)*sqrt(sum(v.cov6b[3:4,3:4]))
min_det_diff_90

### MAKE TABLES

bg_attend <- rbind(
  c(paste(round(res.het.bg.attend$beta[c(1,3)], 2)),sum(XX.het1[,"female"], na.rm=T), 
    paste0(round(res.het.bg.attend[,grep("pchisq",names(res.het.bg.attend))][1], 2))),
  c(sapply(res.het.bg.attend$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.bg.attend$beta[c(2,4)], 2)),sum(XX.het1[,"male"], na.rm=T), ""),
  c(sapply(res.het.bg.attend$SE[c(2,4)], addParens, 2),"",""))

bg_test <- rbind(
  c(paste(round(res.het.bg.test$beta[c(1,3)], 2)),sum(XX.het2[,"female"], na.rm=T), 
    paste0(round(res.het.bg.test[,grep("pchisq",names(res.het.bg.test))][1], 2))),
  c(sapply(res.het.bg.test$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.bg.test$beta[c(2,4)], 2)),sum(XX.het2[,"male"], na.rm=T), ""),
  c(sapply(res.het.bg.test$SE[c(2,4)], addParens, 2),"",""))

maj_attend <- rbind(
  c(paste(round(res.het.maj.attend$beta[c(1,3)], 2)),sum(XX.het3[,"majority_eth"], na.rm=T), 
    paste0(round(res.het.maj.attend[,grep("pchisq",names(res.het.maj.attend))][1], 2))),
  c(sapply(res.het.maj.attend$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.maj.attend$beta[c(2,4)], 2)),sum(XX.het3[,"minority_eth"], na.rm=T), ""),
  c(sapply(res.het.maj.attend$SE[c(2,4)], addParens, 2),"",""))

maj_test <- rbind(
  c(paste(round(res.het.maj.test$beta[c(1,3)], 2)),sum(XX.het4[,"majority_eth"], na.rm=T), 
    paste0(round(res.het.maj.test[,grep("pchisq",names(res.het.maj.test))][1], 2))),
  c(sapply(res.het.maj.test$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.maj.test$beta[c(2,4)], 2)),sum(XX.het4[,"minority_eth"], na.rm=T), ""),
  c(sapply(res.het.maj.test$SE[c(2,4)], addParens, 2),"",""))

cleth_attend <- rbind(
  c(paste(round(res.het.cleth.attend$beta[c(1,3)], 2)),sum(XX.het5[,"same_eth_cl"], na.rm=T), 
    paste0(round(res.het.cleth.attend[,grep("pchisq",names(res.het.cleth.attend))][1], 2))),
  c(sapply(res.het.cleth.attend$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.cleth.attend$beta[c(2,4)], 2)),sum(XX.het5[,"diff_eth_cl"], na.rm=T), ""),
  c(sapply(res.het.cleth.attend$SE[c(2,4)], addParens, 2),"",""))

cleth_test <- rbind(
  c(paste(round(res.het.cleth.test$beta[c(1,3)], 2)),sum(XX.het6[,"same_eth_cl"], na.rm=T), 
    paste0(round(res.het.cleth.test[,grep("pchisq",names(res.het.cleth.test))][1], 2))),
  c(sapply(res.het.cleth.test$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.cleth.test$beta[c(2,4)], 2)),sum(XX.het6[,"diff_eth_cl"], na.rm=T), ""),
  c(sapply(res.het.cleth.test$SE[c(2,4)], addParens, 2),"",""))

Het_Out <- rbind(bg_attend,
      bg_test,
      maj_attend,
      maj_test,
      cleth_attend,
      cleth_test)

Het_Print <- data.frame(Outcome = rep(c("Attendance", rep("",3),
                                    "Test Score", rep("",3)),3),
                        Group = c("Girls","","Boys","","Girls","","Boys","",
                                  "Ethnic majority","","Ethnic minority","","Ethnic majority","","Ethnic minority","",
                                  "CL same ethnicity","","CL diff ethnicity","","CL same ethnicity","","CL diff ethnicity",""),
                        Intercept = Het_Out[,1],
                        Treatment.Effect = Het_Out[,2],
                        N=Het_Out[,3],
                        Het.test.p.value=Het_Out[,4]
                        )

maj_sat <- rbind(
  c(paste(round(res.het.maj.sat$beta[c(1,3)], 2)),sum(XX.het4b[,"majority_eth"], na.rm=T), 
    paste0(round(res.het.maj.sat[,grep("pchisq",names(res.het.maj.sat))][1], 2))),
  c(sapply(res.het.maj.sat$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.maj.sat$beta[c(2,4)], 2)),sum(XX.het4b[,"minority_eth"], na.rm=T), ""),
  c(sapply(res.het.maj.sat$SE[c(2,4)], addParens, 2),"",""))

cleth_sat <- rbind(
  c(paste(round(res.het.cleth.sat$beta[c(1,3)], 2)),sum(XX.het6b[,"same_eth_cl"], na.rm=T), 
    paste0(round(res.het.cleth.sat[,grep("pchisq",names(res.het.cleth.sat))][1], 2))),
  c(sapply(res.het.cleth.sat$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het.cleth.sat$beta[c(2,4)], 2)),sum(XX.het6b[,"diff_eth_cl"], na.rm=T), ""),
  c(sapply(res.het.cleth.sat$SE[c(2,4)], addParens, 2),"",""))

Het_Out_sat <- rbind(maj_sat, cleth_sat)

Het_Print_sat <- data.frame(Outcome = rep(c("HH Sat. w. Access", rep("",3)),2),
                        Group = c("Ethnic majority","","Ethnic minority","",
                                  "CL same ethnicity","","CL diff ethnicity",""),
                        Intercept = Het_Out_sat[,1],
                        Treatment.Effect = Het_Out_sat[,2],
                        N=Het_Out_sat[,3],
                        Het.test.p.value=Het_Out_sat[,4]
)

sink(file="tabs-figs/equity_htes.tex")
print(xtable(rbind(Het_Print, Het_Print_sat),
             caption="\\label{tab:equity_hte} Heterogeneous Treatment Effects by Gender and Ethnic Status"),
      include.rownames=F,
      caption.placement = "top",
      hline.after = c(-1,0,8,16,24, 32))
sink()


##############################################################################
### TABLE A11: HETEROGENEOUS TREATMENT EFFECTS BY CL HAVING SCHOOL AGE CHILDREN
##############################################################################

# Heterogeneity Test for CL Having School-Aged Children versus Not, Attendance

subset.het7<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"ros_attend"]))&(!is.na(dat.hh$wt))

y.tr.het7<-dat.hh[subset.het7, "ros_attend"]

tmp.het7<-cbind(dat.hh[,c("has_child813", "no_child813")]
                , sapply(dat.hh[,c("has_child813", "no_child813")]
                         ,function(x) x*dat.hh$HAND))

colnames(tmp.het7)[3:4] <- c("sameXhand","diffXhand")

XX.het7<-as.matrix(cbind(tmp.het7[subset.het7, ]
                         , sapply(dat.hh[subset.het7, cov2.hh.int[-c(2:4)]], dm)))

lm.het7<-lm(formula(paste("y.tr.het7", "XX.het7", sep="~0+"))
            , weights=dat.hh$wt[subset.het7])

res.het7<-coef_test(lm.het7, vcov=vcovCR(lm.het7, cluster=dat.hh$CLUSTER[subset.het7], type="CR2"))

#full results [for appendix]
res.het7.full<-as.data.frame(res.het7)

#main results without all the covariates [for main appendix]
res.het7<-as.data.frame(res.het7[c(1:4),])
print(summary(lm.het7))
t.het7  <- sapply(res.het7$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het7<- length(c("has_child813", "no_child813"))
constraint.mat.het7<- matrix(rep(0, dim(XX.het7)[2]*(k.dummy.het7-1)) , ncol=dim(XX.het7)[2])
for( i in 1:(k.dummy.het7-1) ) {
  print(sum(subset.het7))
  print(k.dummy.het7)
  print(paste("dim constraint.mat.het7=", dim(constraint.mat.het7)))
  constraint.mat.het7[i, i+k.dummy.het7  ] <-  1
  constraint.mat.het7[i, i+k.dummy.het7+1] <- -1
}
print(constraint.mat.het7)
wald.het7 <- Wald_test(lm.het7, constraint.mat.het7, cluster=dat.hh$CLUSTER[subset.het7] , vcov="CR2")

v.cov7<- vcovCR(lm.het7, cluster=dat.hh$CLUSTER[subset.het7],type="CR2" )
point.est7  <-as.vector(constraint.mat.het7%*%as.vector(coef(lm.het7)))
v.point.est7<- (constraint.mat.het7%*%v.cov7%*%t(constraint.mat.het7))
test.stat7<-point.est7%*%solve(v.point.est7)%*%point.est7
pchisq(test.stat7, df=2, lower.tail=FALSE) # this is the heterogeneity p-value in the table

res.het7<- cbind(res.het7, wald.het7, pchisq(test.stat7, df=2, lower.tail=FALSE))

# Heterogeneity Test for CL Having School-Aged Children versus Not, Math and Reading Score

subset.het8<-(is.na(eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh$ros_age0813==1&dat.hh$TREAT==1)'))&(!is.na(dat.hh[,"std_mathread"]))&(!is.na(dat.hh$wt))

y.tr.het8<-dat.hh[subset.het8, "std_mathread"]

tmp.het8<-cbind(dat.hh[,c("has_child813", "no_child813")]
                , sapply(dat.hh[,c("has_child813", "no_child813")]
                         ,function(x) x*dat.hh$HAND))

colnames(tmp.het8)[3:4] <- c("sameXhand","diffXhand")

XX.het8<-as.matrix(cbind(tmp.het8[subset.het8, ]
                         , sapply(dat.hh[subset.het8, cov2.hh.int[-c(2:4)]], dm)))

lm.het8<-lm(formula(paste("y.tr.het8", "XX.het8", sep="~0+"))
            , weights=dat.hh$wt[subset.het8])

res.het8<-coef_test(lm.het8, vcov=vcovCR(lm.het8, cluster=dat.hh$CLUSTER[subset.het8], type="CR2"))

#full results [for appendix]
res.het8.full<-as.data.frame(res.het8)

#main results without all the covariates [for main appendix]
res.het8<-as.data.frame(res.het8[c(1:4),])
print(summary(lm.het8))
t.het8  <- sapply(res.het8$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het8<- length(c("has_child813", "no_child813"))
constraint.mat.het8<- matrix(rep(0, dim(XX.het8)[2]*(k.dummy.het8-1)) , ncol=dim(XX.het8)[2])
for( i in 1:(k.dummy.het8-1) ) {
  print(sum(subset.het8))
  print(k.dummy.het8)
  print(paste("dim constraint.mat.het8=", dim(constraint.mat.het8)))
  constraint.mat.het8[i, i+k.dummy.het8  ] <-  1
  constraint.mat.het8[i, i+k.dummy.het8+1] <- -1
}
print(constraint.mat.het8)
wald.het8 <- Wald_test(lm.het8, constraint.mat.het8, cluster=dat.hh$CLUSTER[subset.het8] , vcov="CR2")

v.cov8<- vcovCR(lm.het8, cluster=dat.hh$CLUSTER[subset.het8],type="CR2" )
point.est8  <-as.vector(constraint.mat.het8%*%as.vector(coef(lm.het8)))
v.point.est8<- (constraint.mat.het8%*%v.cov8%*%t(constraint.mat.het8))
test.stat8<-point.est8%*%solve(v.point.est8)%*%point.est8
pchisq(test.stat8, df=2, lower.tail=FALSE) # this is the heterogeneity p-value in the table

res.het8<- cbind(res.het8, wald.het8, pchisq(test.stat8, df=2, lower.tail=FALSE))

# HOUSEHOLD SATISFACTION AND CONFIDENCE OUTCOMES

# Heterogeneity Test for CL Having School-Aged Children versus Not, HH Satisfaction with Access

subset.het9<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"satisfaction_access_score"]))&(!is.na(dat.hh$wt))

y.temp.het9<- dat.hh[subset.het9, "satisfaction_access_score"]
wms.het9<-wtd.mean.sd(y.temp.het9[dat.hh$HAND[subset.het9]==0&dat.hh$TREAT[subset.het9]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subset.het9])
y.tr.het9<-(y.temp.het9-wms.het9$mean)/wms.het9$sd

tmp.het9<-cbind(dat.hh[,c("has_child813", "no_child813")]
                , sapply(dat.hh[,c("has_child813", "no_child813")]
                         ,function(x) x*dat.hh$HAND))

colnames(tmp.het9)[3:4] <- c("sameXhand","diffXhand")

XX.het9<-as.matrix(cbind(tmp.het9[subset.het9, ]
                         , sapply(dat.hh[subset.het9, cov2.hh.int[-c(2:4)]], dm)))

lm.het9<-lm(formula(paste("y.tr.het9", "XX.het9", sep="~0+"))
            , weights=dat.hh$wt[subset.het9])

res.het9<-coef_test(lm.het9, vcov=vcovCR(lm.het9, cluster=dat.hh$CLUSTER[subset.het9], type="CR2"))

#full results [for appendix]
res.het9.full<-as.data.frame(res.het9)

#main results without all the covariates [for main appendix]
res.het9<-as.data.frame(res.het9[c(1:4),])
print(summary(lm.het9))
t.het9  <- sapply(res.het9$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het9<- length(c("has_child813", "no_child813"))
constraint.mat.het9<- matrix(rep(0, dim(XX.het9)[2]*(k.dummy.het9-1)) , ncol=dim(XX.het9)[2])
for( i in 1:(k.dummy.het9-1) ) {
  print(sum(subset.het9))
  print(k.dummy.het9)
  print(paste("dim constraint.mat.het9=", dim(constraint.mat.het9)))
  constraint.mat.het9[i, i+k.dummy.het9  ] <-  1
  constraint.mat.het9[i, i+k.dummy.het9+1] <- -1
}
print(constraint.mat.het9)
wald.het9 <- Wald_test(lm.het9, constraint.mat.het9, cluster=dat.hh$CLUSTER[subset.het9] , vcov="CR2")

v.cov9<- vcovCR(lm.het9, cluster=dat.hh$CLUSTER[subset.het9],type="CR2" )
point.est9  <-as.vector(constraint.mat.het9%*%as.vector(coef(lm.het9)))
v.point.est9<- (constraint.mat.het9%*%v.cov9%*%t(constraint.mat.het9))
test.stat9<-point.est9%*%solve(v.point.est9)%*%point.est9
pchisq(test.stat9, df=2, lower.tail=FALSE) # this is the heterogeneity p-value in the table

res.het9<- cbind(res.het9, wald.het9, pchisq(test.stat9, df=2, lower.tail=FALSE))

# Heterogeneity Test for CL Having School-Aged Children versus Not, Confidence in Local Institutions

subset.het10<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"sustainability_confidence_score"]))&(!is.na(dat.hh$wt))

y.temp.het10<- dat.hh[subset.het10, "sustainability_confidence_score"]
wms.het10<-wtd.mean.sd(y.temp.het10[dat.hh$HAND[subset.het10]==0&dat.hh$TREAT[subset.het10]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subset.het10])
y.tr.het10<-(y.temp.het10-wms.het10$mean)/wms.het10$sd

tmp.het10<-cbind(dat.hh[,c("has_child813", "no_child813")]
                 , sapply(dat.hh[,c("has_child813", "no_child813")]
                          ,function(x) x*dat.hh$HAND))

colnames(tmp.het10)[3:4] <- c("sameXhand","diffXhand")

XX.het10<-as.matrix(cbind(tmp.het10[subset.het10, ]
                          , sapply(dat.hh[subset.het10, cov2.hh.int[-c(2:4)]], dm)))

lm.het10<-lm(formula(paste("y.tr.het10", "XX.het10", sep="~0+"))
             , weights=dat.hh$wt[subset.het10])

res.het10<-coef_test(lm.het10, vcov=vcovCR(lm.het10, cluster=dat.hh$CLUSTER[subset.het10], type="CR2"))

#full results [for appendix]
res.het10.full<-as.data.frame(res.het10)

#main results without all the covariates [for main appendix]
res.het10<-as.data.frame(res.het10[c(1:4),])
print(summary(lm.het10))
t.het10  <- sapply(res.het10$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het10<- length(c("has_child813", "no_child813"))
constraint.mat.het10<- matrix(rep(0, dim(XX.het10)[2]*(k.dummy.het10-1)) , ncol=dim(XX.het10)[2])
for( i in 1:(k.dummy.het10-1) ) {
  print(sum(subset.het10))
  print(k.dummy.het10)
  print(paste("dim constraint.mat.het10=", dim(constraint.mat.het10)))
  constraint.mat.het10[i, i+k.dummy.het10  ] <-  1
  constraint.mat.het10[i, i+k.dummy.het10+1] <- -1
}
print(constraint.mat.het10)
wald.het10 <- Wald_test(lm.het10, constraint.mat.het10, cluster=dat.hh$CLUSTER[subset.het10] , vcov="CR2")

v.cov10<- vcovCR(lm.het10, cluster=dat.hh$CLUSTER[subset.het10],type="CR2" )
point.est10  <-as.vector(constraint.mat.het10%*%as.vector(coef(lm.het10)))
v.point.est10<- (constraint.mat.het10%*%v.cov10%*%t(constraint.mat.het10))
test.stat10<-point.est10%*%solve(v.point.est10)%*%point.est10
pchisq(test.stat10, df=2, lower.tail=FALSE) # this is the heterogeneity p-value in the table

res.het10<- cbind(res.het10, wald.het10, pchisq(test.stat10, df=2, lower.tail=FALSE))

# TEACHER MOTIVATION AND PERFORMANCE 

# Heterogeneity Test for CL Having School-Aged Children versus Not, Teacher Attendance

subset.het11<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"teacher_attend_score"]))&(!is.na(dat.hh$wt))

y.temp.het11<-dat.hh[subset.het11, "teacher_attend_score"]
wms.het11<-wtd.mean.sd(y.temp.het11[dat.hh$HAND[subset.het11]==0&dat.hh$TREAT[subset.het11]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subset.het11])
y.tr.het11<-(y.temp.het11-wms.het11$mean)/wms.het11$sd

tmp.het11<-cbind(dat.hh[,c("has_child813", "no_child813")]
                 , sapply(dat.hh[,c("has_child813", "no_child813")]
                          ,function(x) x*dat.hh$HAND))

colnames(tmp.het11)[3:4] <- c("sameXhand","diffXhand")

XX.het11<-as.matrix(cbind(tmp.het11[subset.het11, ]
                          , sapply(dat.hh[subset.het11, cov2.hh.int[-c(2:4)]], dm)))

lm.het11<-lm(formula(paste("y.tr.het11", "XX.het11", sep="~0+"))
             , weights=dat.hh$wt[subset.het11])

res.het11<-coef_test(lm.het11, vcov=vcovCR(lm.het11, cluster=dat.hh$CLUSTER[subset.het11], type="CR2"))

#full results [for appendix]
res.het11.full<-as.data.frame(res.het11)

#main results without all the covariates [for main appendix]
res.het11<-as.data.frame(res.het11[c(1:4),])
print(summary(lm.het11))
t.het11  <- sapply(res.het11$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het11<- length(c("has_child813", "no_child813"))
constraint.mat.het11<- matrix(rep(0, dim(XX.het11)[2]*(k.dummy.het11-1)) , ncol=dim(XX.het11)[2])
for( i in 1:(k.dummy.het11-1) ) {
  print(sum(subset.het11))
  print(k.dummy.het11)
  print(paste("dim constraint.mat.het11=", dim(constraint.mat.het11)))
  constraint.mat.het11[i, i+k.dummy.het11  ] <-  1
  constraint.mat.het11[i, i+k.dummy.het11+1] <- -1
}
print(constraint.mat.het11)
wald.het11 <- Wald_test(lm.het11, constraint.mat.het11, cluster=dat.hh$CLUSTER[subset.het11] , vcov="CR2")

v.cov11<- vcovCR(lm.het11, cluster=dat.hh$CLUSTER[subset.het11],type="CR2" )
point.est11  <-as.vector(constraint.mat.het11%*%as.vector(coef(lm.het11)))
v.point.est11<- (constraint.mat.het11%*%v.cov11%*%t(constraint.mat.het11))
test.stat11<-point.est11%*%solve(v.point.est11)%*%point.est11
pchisq(test.stat11, df=2, lower.tail=FALSE) # this is the heterogeneity p-value in the table

res.het11<- cbind(res.het11, wald.het11, pchisq(test.stat11, df=2, lower.tail=FALSE))

# Heterogeneity Test for CL Having School-Aged Children versus Not, Teacher Quality

subset.het12<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"teacher_perception_score"]))&(!is.na(dat.hh$wt))

y.temp.het12<-dat.hh[subset.het12, "teacher_perception_score"]
wms.het12<-wtd.mean.sd(y.temp.het12[dat.hh$HAND[subset.het12]==0&dat.hh$TREAT[subset.het12]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subset.het12])
y.tr.het12<-(y.temp.het12-wms.het12$mean)/wms.het11$sd

tmp.het12<-cbind(dat.hh[,c("has_child813", "no_child813")]
                 , sapply(dat.hh[,c("has_child813", "no_child813")]
                          ,function(x) x*dat.hh$HAND))

colnames(tmp.het12)[3:4] <- c("sameXhand","diffXhand")

XX.het12<-as.matrix(cbind(tmp.het12[subset.het12, ]
                          , sapply(dat.hh[subset.het12, cov2.hh.int[-c(2:4)]], dm)))

lm.het12<-lm(formula(paste("y.tr.het12", "XX.het12", sep="~0+"))
             , weights=dat.hh$wt[subset.het12])

res.het12<-coef_test(lm.het12, vcov=vcovCR(lm.het12, cluster=dat.hh$CLUSTER[subset.het12], type="CR2"))

#full results [for appendix]
res.het12.full<-as.data.frame(res.het12)

#main results without all the covariates [for main appendix]
res.het12<-as.data.frame(res.het12[c(1:4),])
print(summary(lm.het12))
t.het12  <- sapply(res.het12$df, function(d) qt(1-(1-0.9)/2, df=d))

k.dummy.het12<- length(c("has_child813", "no_child813"))
constraint.mat.het12<- matrix(rep(0, dim(XX.het12)[2]*(k.dummy.het12-1)) , ncol=dim(XX.het12)[2])
for( i in 1:(k.dummy.het12-1) ) {
  print(sum(subset.het11))
  print(k.dummy.het12)
  print(paste("dim constraint.mat.het12=", dim(constraint.mat.het12)))
  constraint.mat.het12[i, i+k.dummy.het12  ] <-  1
  constraint.mat.het12[i, i+k.dummy.het12+1] <- -1
}
print(constraint.mat.het12)
wald.het12 <- Wald_test(lm.het12, constraint.mat.het12, cluster=dat.hh$CLUSTER[subset.het12] , vcov="CR2")

v.cov12<- vcovCR(lm.het12, cluster=dat.hh$CLUSTER[subset.het12],type="CR2" )
point.est12  <-as.vector(constraint.mat.het12%*%as.vector(coef(lm.het12)))
v.point.est12<- (constraint.mat.het12%*%v.cov12%*%t(constraint.mat.het12))
test.stat12<-v.point.est12%*%solve(v.point.est12)%*%v.point.est12
pchisq(test.stat12, df=2, lower.tail=FALSE) # this is the heterogeneity p-value in the table

res.het12<- cbind(res.het12, wald.het12, pchisq(test.stat12, df=2, lower.tail=FALSE))

####################
### MAKE TABLE
####################

cl_child_attend <- rbind(
  c(paste(round(res.het7$beta[c(1,3)], 2)),sum(XX.het7[,"has_child813"], na.rm=T), 
    paste0(round(res.het7[,grep("pchisq",names(res.het7))][1], 2))),
  c(sapply(res.het7$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het7$beta[c(2,4)], 2)),sum(XX.het7[,"no_child813"], na.rm=T), ""),
  c(sapply(res.het7$SE[c(2,4)], addParens, 2),"",""))

cl_child_test <- rbind(
  c(paste(round(res.het8$beta[c(1,3)], 2)),sum(XX.het8[,"has_child813"], na.rm=T), 
    paste0(round(res.het8[,grep("pchisq",names(res.het8))][1], 2))),
  c(sapply(res.het8$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het8$beta[c(2,4)], 2)),sum(XX.het8[,"no_child813"], na.rm=T), ""),
  c(sapply(res.het8$SE[c(2,4)], addParens, 2),"",""))

cl_child_hh_sat <- rbind(
  c(paste(round(res.het9$beta[c(1,3)], 2)),sum(XX.het9[,"has_child813"], na.rm=T), 
    paste0(round(res.het9[,grep("pchisq",names(res.het9))][1], 2))),
  c(sapply(res.het9$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het9$beta[c(2,4)], 2)),sum(XX.het9[,"no_child813"], na.rm=T), ""),
  c(sapply(res.het9$SE[c(2,4)], addParens, 2),"",""))

cl_child_hh_conf <- rbind(
  c(paste(round(res.het10$beta[c(1,3)], 2)),sum(XX.het10[,"has_child813"], na.rm=T), 
    paste0(round(res.het10[,grep("pchisq",names(res.het10))][1], 2))),
  c(sapply(res.het10$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het10$beta[c(2,4)], 2)),sum(XX.het10[,"no_child813"], na.rm=T), ""),
  c(sapply(res.het10$SE[c(2,4)], addParens, 2),"",""))

cl_child_hh_t_attend <- rbind(
  c(paste(round(res.het11$beta[c(1,3)], 2)),sum(XX.het11[,"has_child813"], na.rm=T), 
    paste0(round(res.het11[,grep("pchisq",names(res.het11))][1], 2))),
  c(sapply(res.het11$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het11$beta[c(2,4)], 2)),sum(XX.het11[,"no_child813"], na.rm=T), ""),
  c(sapply(res.het11$SE[c(2,4)], addParens, 2),"",""))

cl_child_hh_t_qual <- rbind(
  c(paste(round(res.het12$beta[c(1,3)], 2)),sum(XX.het12[,"has_child813"], na.rm=T), 
    paste0(round(res.het12[,grep("pchisq",names(res.het12))][1], 2))),
  c(sapply(res.het12$SE[c(1,3)], addParens, 2),"",""),
  c(paste(round(res.het12$beta[c(2,4)], 2)),sum(XX.het12[,"no_child813"], na.rm=T), ""),
  c(sapply(res.het12$SE[c(2,4)], addParens, 2),"",""))

Het_cl_child_Out <- rbind(cl_child_attend,
                          cl_child_test,
                          cl_child_hh_sat,
                          cl_child_hh_conf,
                          cl_child_hh_t_attend,
                          cl_child_hh_t_qual)

Het_cl_child_Print <- data.frame(Outcome = c("Attendance", rep("",3),
                                              "Test score", rep("",3),
                                              "HH satisfaction with access",rep("",3),
                                              "HH confidence in local instns.", rep("",3),
                                              "HH perceived teacher attendance", rep("",3),
                                              "HH perceived teacher quality", rep("",3)),
                        Group = rep(c("Has children","","No children",""), 3),
                        Intercept = Het_cl_child_Out[,1],
                        Treatment.Effect = Het_cl_child_Out[,2],
                        N=Het_cl_child_Out[,3],
                        Het.test.p.value=Het_cl_child_Out[,4])

sink(file="tabs-figs/cl_school_age_child_hh_htes.tex")
print(xtable(Het_cl_child_Print,
             caption="\\label{tab:cl_child_htes} Heterogeneous Treatment Effects by Community Leader having School-age Children"),
      include.rownames=F,
      caption.placement = "top",
      hline.after = c(-1,0,4,8,12,16,20,24))
sink()

#########################################################################################
### COMMUNITY ENGAGEMENT: Tables A12 and A13
#########################################################################################


# Able to name head of closest government hub school

subsetC<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"q65_b"]))&(!is.na(dat.hh$wt))

y.tmpC<-dat.hh[subsetC, "q65_b"]
wmsC<-wtd.mean.sd(y.tmpC[dat.hh$HAND[subsetC]==0&dat.hh$TREAT[subsetC]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subsetC])

# ordering of covariate list seems to matter 
XXC<-as.matrix(cbind(dat.hh[subsetC, c("TREAT", "HAND")], sapply(dat.hh[subsetC, cov2.hh], dm)))

lmC<-lm( formula(paste("y.tmpC", "XXC", sep="~")),  weights=dat.hh$wt[subsetC])

res_name_hub<-coef_test(lmC, vcov=vcovCR(lmC, cluster=dat.hh$CLUSTER[subsetC], type="CR2"))
res_name_hub <-as.data.frame(res_name_hub[1:2,])
res_name_hub$N <- length(residuals(lmC))


# Able to name district education director

subsetC<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"q66_b"]))&(!is.na(dat.hh$wt))

y.tmpC<-dat.hh[subsetC, "q66_b"]
wmsC<-wtd.mean.sd(y.tmpC[dat.hh$HAND[subsetC]==0&dat.hh$TREAT[subsetC]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subsetC])

# ordering of covariate list seems to matter 
XXC<-as.matrix(cbind(dat.hh[subsetC, c("TREAT", "HAND")], sapply(dat.hh[subsetC, cov2.hh], dm)))

lmC<-lm( formula(paste("y.tmpC", "XXC", sep="~")),  weights=dat.hh$wt[subsetC])

res_name_ded<-coef_test(lmC, vcov=vcovCR(lmC, cluster=dat.hh$CLUSTER[subsetC], type="CR2"))
res_name_ded <-as.data.frame(res_name_ded[1:2,])
res_name_ded$N <- length(residuals(lmC))

# Able to name the CDC head

subsetC<-(is.na(eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh$TREAT==1&dat.hh$within.hh.id==1)'))&(!is.na(dat.hh[,"q68_b"]))&(!is.na(dat.hh$wt))

y.tmpC<-dat.hh[subsetC, "q68_b"]
wmsC<-wtd.mean.sd(y.tmpC[dat.hh$HAND[subsetC]==0&dat.hh$TREAT[subsetC]==1], dat.hh$wt[dat.hh$HAND==0&dat.hh$TREAT==1&subsetC])

# ordering of covariate list seems to matter 
XXC<-as.matrix(cbind(dat.hh[subsetC, c("TREAT", "HAND")], sapply(dat.hh[subsetC, cov2.hh], dm)))

lmC<-lm( formula(paste("y.tmpC", "XXC", sep="~")),  weights=dat.hh$wt[subsetC])

res_name_CDC<-coef_test(lmC, vcov=vcovCR(lmC, cluster=dat.hh$CLUSTER[subsetC], type="CR2"))
res_name_CDC <-as.data.frame(res_name_CDC[1:2,]) 
res_name_CDC$N <- length(residuals(lmC))


name_leaders <- cbind(
  c("Intercept",
    "",
    "Treatment Effect",
    "",
    "N"),
  c(rbind(sprintf("%1.2f", res_name_hub$beta),
    addParens(res_name_hub$SE, 2)), 
    res_name_hub$N[1]),
  c(rbind(sprintf("%1.2f", res_name_ded$beta),
    addParens(res_name_ded$SE, 2)), 
    res_name_ded$N[1]),
  c(rbind(sprintf("%1.2f", res_name_CDC$beta),
    addParens(res_name_CDC$SE, 2)),
    res_name_CDC$N[1])
)

colnames(name_leaders) <- c(" ",
                            "Name Hub School Head",
                            "Name Distr. Ed. Dir.",
                            "Name CDC Head")

sink(file="tabs-figs/hh_name_leaders.tex")
print(xtable(name_leaders,
             caption="\\label{tab:name_leaders} Share of household heads who can correctly name local education CDC leaders"),
      include.rownames=F,
      caption.placement = "top",
      hline.after = c(-1,0,4))
sink()


# Value of talking to CDC member for addresing education problems

library(survey)

svy_hh <- svydesign(id=~CLUSTER+HHID,
                    strata=~Province, 
                    weights=~wt, 
                    data=dat.hh)

value_cdc_tab <-  svytable(~q59c_r+HAND, design=svy_hh, Ntotal=1)
value_cdc_norm <- t(as.matrix(apply(value_cdc_tab, 2, sum)))%x%rep(1, nrow(value_cdc_tab))
value_cdc_out = cbind(value_cdc_tab/value_cdc_norm,
                      svytable(~q59c_r, design=svy_hh, Ntotal=1))

colnames(value_cdc_out) <- c("Control","Treated","All")
rownames(value_cdc_out) <- c("Not useful at all",
                             "Not very useful",
                             "Refused/Don't Know",
                             "Somewhat useful",
                             "Very useful")

sink(file="tabs-figs/hh_value_cdc.tex")
print(xtable(value_cdc_out,
             caption="\\label{tab:value_cdc} Share of household heads responding to how useful they think it would be to talk to the CDC about problems with educating their children"),
      include.rownames=T,
      caption.placement = "top",
      hline.after = c(-1,0,5))
sink()

#########################################################################################
### CHECKING FOR LINGERING CAPACITY DEFICITS
#########################################################################################

#########################################################################################
### TABLE A14: VILLAGE-LEVEL MANAGEMENT CA SCORES AND MAIN CHILD & AGENCY OUTCOMES 
#########################################################################################

# aged 8-13 attendance outcome with child cov2 list

subset65<-(is.na(eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)'))&(!is.na(dat.hh.ca[,"ros_attend"]))&(!is.na(dat.hh.ca$wt))
y.tr65 <- dat.hh.ca[subset65, "ros_attend"]
XX65<-as.matrix(cbind(dat.hh.ca[subset65, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset65, cov2.child], dm)))
lm65<-lm( formula(paste("y.tr65", "XX65", sep="~")),  weights=dat.hh.ca$wt[subset65])
res65<-coef_test(lm65, vcov=vcovCR(lm65, cluster=dat.hh.ca$CLUSTER[subset65], type="CR2"))
print(res65)

#for supplmentary appendix
res65_full<-as.data.frame(res65) 

res65<-as.data.frame(res65[2:4,]) # keep second to fourth row of output 

# aged 8-13 std_mathread with child cov2 list

subset66<-(is.na(eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)'))&(!is.na(dat.hh.ca[,"std_mathread"]))&(!is.na(dat.hh.ca$wt))
y.tr66 <- dat.hh.ca[subset66, "std_mathread"]
XX66<-as.matrix(cbind(dat.hh.ca[subset66, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset66, cov2.child], dm)))
lm66<-lm( formula(paste("y.tr66", "XX66", sep="~")),  weights=dat.hh.ca$wt[subset66])
res66<-coef_test(lm66, vcov=vcovCR(lm66, cluster=dat.hh.ca$CLUSTER[subset66], type="CR2"))
print(res66)

#for supplmentary appendix
res66_full<-as.data.frame(res66) 

res66<-as.data.frame(res66[2:4,]) # keep second row of output 

# household sustainability_confidence_score

subset67<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"sustainability_confidence_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp67<-dat.hh.ca[subset67, "sustainability_confidence_score"]
wms67<-wtd.mean.sd(y.tmp67[dat.hh.ca$HAND[subset67]==0&dat.hh.ca$TREAT[subset67]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset67])
y.tr67<-(dat.hh.ca[subset67, "sustainability_confidence_score"]-wms67$mean)/wms67$sd
XX67<-as.matrix(cbind(dat.hh.ca[subset67, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset67, cov2.hh], dm)))
lm67<-lm( formula(paste("y.tr67", "XX67", sep="~")),  weights=dat.hh.ca$wt[subset67])
res67<-coef_test(lm67, vcov=vcovCR(lm67, cluster=dat.hh.ca$CLUSTER[subset67], type="CR2"))
print(res67)

#for supplmentary appendix
res67_full<-as.data.frame(res67) 

res67<-as.data.frame(res67[2:4,]) # keep to fourth second row of output 

# household teacher_perception_score

subset68<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"teacher_perception_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp68<-dat.hh.ca[subset68, "teacher_perception_score"]
wms68<-wtd.mean.sd(y.tmp68[dat.hh.ca$HAND[subset68]==0&dat.hh.ca$TREAT[subset68]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset68])
y.tr68<-(dat.hh.ca[subset68, "teacher_perception_score"]-wms68$mean)/wms68$sd
XX68<-as.matrix(cbind(dat.hh.ca[subset68, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset68, cov2.hh], dm)))
lm68<-lm( formula(paste("y.tr68", "XX68", sep="~")),  weights=dat.hh.ca$wt[subset68])
res68<-coef_test(lm68, vcov=vcovCR(lm68, cluster=dat.hh.ca$CLUSTER[subset68], type="CR2"))
print(res68)

#for supplmentary appendix
res68_full<-as.data.frame(res68) 

res68<-as.data.frame(res68[2:4,]) # keep to fourth second row of output 

# household teacher_attend_score

subset69<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"teacher_attend_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp69<-dat.hh.ca[subset69, "teacher_attend_score"]
wms69<-wtd.mean.sd(y.tmp69[dat.hh.ca$HAND[subset69]==0&dat.hh.ca$TREAT[subset69]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset69])
y.tr69<-(dat.hh.ca[subset69, "teacher_attend_score"]-wms69$mean)/wms69$sd
XX69<-as.matrix(cbind(dat.hh.ca[subset69, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset69, cov2.hh], dm)))
lm69<-lm( formula(paste("y.tr69", "XX69", sep="~")),  weights=dat.hh.ca$wt[subset69])
res69<-coef_test(lm69, vcov=vcovCR(lm69, cluster=dat.hh.ca$CLUSTER[subset69], type="CR2"))
print(res69)

#for supplmentary appendix
res69_full<-as.data.frame(res69) 

res69<-as.data.frame(res69[2:4,]) # keep second to fourth row of output 

# CL outcome: classroom funds, sum score

subset70<-(is.na(eval(parse(text='(dat.cl.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.ca$TREAT==1)'))&(!is.na(dat.cl.ca[,"cl_funds_supplies_score"]))&(!is.na(dat.cl.ca$wt))
y.tr70<-(dat.cl.ca[subset70, "cl_funds_supplies_score"]-
           mean(dat.cl.ca[subset70&dat.cl.ca$HAND==0, "cl_funds_supplies_score"], na.rm=TRUE))/sd(dat.cl.ca[subset70&dat.cl.ca$HAND==0, "cl_funds_supplies_score"], na.rm=TRUE)
XX70<-as.matrix(cbind(dat.cl.ca[subset70, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], sapply(dat.cl.ca[subset70, cov1.cl], dm)))
lm70<-lm( formula(paste("y.tr70", "XX70", sep="~")),  weights=dat.cl.ca$wt[subset70])
res70<-coef_test(lm70, vcov=vcovCR(lm70, cluster=dat.cl.ca$CLUSTER[subset70], type="CR2"))
print(res70)

#for supplementary appendix
res70_full<-as.data.frame(res70)

res70<-as.data.frame(res70[2:4,]) # keep second to fourth row of output 

# Teacher outcome 1: combined fund application index

subset71<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_score.COMBO"]))&(!is.na(dat.ts.ca$wt))
y.tr71<-(dat.ts.ca[subset71, "t_funds_score.COMBO"]-
           mean(dat.ts.ca[subset71&dat.ts.ca$HAND==0, "t_funds_score.COMBO"], na.rm=TRUE))/sd(dat.ts.ca[subset71&dat.ts.ca$HAND==0, "t_funds_score.COMBO"], na.rm=TRUE)
cv71<-dm(dat.ts.ca[subset71, cov1.ts])
XX71<-as.matrix(cbind(dat.ts.ca[subset71, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], cv71))
lm71<-lm( formula(paste("y.tr71", "XX71", sep="~")),  weights=dat.ts.ca$wt[subset71])
res71<-coef_test(lm71, vcov=vcovCR(lm71, cluster=dat.ts.ca$CLUSTER[subset71], type="CR2"))
print(res71)

#for supplementary appendix
res71_full<-as.data.frame(res71)

res71<-as.data.frame(res71[2:4,]) # keep second to fourth row of output 

# Teacher outcome 2: classroom supplies

subset72<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_supplies_score"]))&(!is.na(dat.ts.ca$wt))
y.tr72<-(dat.ts.ca[subset72, "t_funds_supplies_score"]-
           mean(dat.ts.ca[subset72&dat.ts.ca$HAND==0, "t_funds_supplies_score"], na.rm=TRUE))/sd(dat.ts.ca[subset72&dat.ts.ca$HAND==0, "t_funds_supplies_score"], na.rm=TRUE)
cv72<-dm(dat.ts.ca[subset72, cov1.ts])
XX72<-as.matrix(cbind(dat.ts.ca[subset72, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], cv72))
lm72<-lm( formula(paste("y.tr72", "XX72", sep="~")),  weights=dat.ts.ca$wt[subset72])
res72<-coef_test(lm72, vcov=vcovCR(lm72, cluster=dat.ts.ca$CLUSTER[subset72], type="CR2"))
print(res72)

#for supplementary appendix
res72_full<-as.data.frame(res72)

res72<-as.data.frame(res72[2:4,]) # keep second to fourth row of output 

# Teacher outcome 3: combined motivation index

subset73<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_motivation_score.COMBO"]))&(!is.na(dat.ts.ca$wt))
y.tr73<-(dat.ts.ca[subset73, "t_motivation_score.COMBO"]-
           mean(dat.ts.ca[subset73&dat.ts.ca$HAND==0, "t_motivation_score.COMBO"], na.rm=TRUE))/sd(dat.ts.ca[subset73&dat.ts.ca$HAND==0, "t_motivation_score.COMBO"], na.rm=TRUE)
cv73<-dm(dat.ts.ca[subset73, cov1.ts])
XX73<-as.matrix(cbind(dat.ts.ca[subset73, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], cv73))
lm73<-lm( formula(paste("y.tr73", "XX73", sep="~")),  weights=dat.ts.ca$wt[subset73])
res73<-coef_test(lm73, vcov=vcovCR(lm73, cluster=dat.ts.ca$CLUSTER[subset73], type="CR2"))
print(res73)

#for supplementary appendix
res73_full<-as.data.frame(res73)

res73<-as.data.frame(res73[2:4,]) # keep second row of output 

# Teacher outcome 4: teacher paid regularly

subset74<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_regularpay_score"]))&(!is.na(dat.ts.ca$wt))
y.tr74<-(dat.ts.ca[subset74, "t_funds_regularpay_score"]-
           mean(dat.ts.ca[subset74&dat.ts.ca$HAND==0, "t_funds_regularpay_score"], na.rm=TRUE))/sd(dat.ts.ca[subset74&dat.ts.ca$HAND==0, "t_funds_regularpay_score"], na.rm=TRUE)
cv74<-dm(dat.ts.ca[subset74, cov1.ts])
XX74<-as.matrix(cbind(dat.ts.ca[subset74, c("TREAT", "HAND", "village_ca_sum_score_std", "HAND_village_ca_sum_score_std", "HAND_kapisa", "HAND_parwan")], cv74))
lm74<-lm( formula(paste("y.tr74", "XX74", sep="~")),  weights=dat.ts.ca$wt[subset74])
res74<-coef_test(lm74, vcov=vcovCR(lm74, cluster=dat.ts.ca$CLUSTER[subset74], type="CR2"))
print(res74)

#for supplementary appendix
res74_full<-as.data.frame(res74)

res74<-as.data.frame(res74[2:4,]) # keep second row of output 

capacity1_out <- t(
  cbind(
  cbind(paste(c(round(res65$beta, 2),length(lm65$residuals))),c(sapply(res65$SE, addParens, 2),"")),
  cbind(paste(c(round(res66$beta, 2),length(lm66$residuals))),c(sapply(res66$SE, addParens, 2),"")),
  cbind(paste(c(round(res67$beta, 2),length(lm67$residuals))),c(sapply(res67$SE, addParens, 2),"")),
  cbind(paste(c(round(res68$beta, 2),length(lm68$residuals))),c(sapply(res68$SE, addParens, 2),"")),
  cbind(paste(c(round(res69$beta, 2),length(lm69$residuals))),c(sapply(res69$SE, addParens, 2),"")),
  cbind(paste(c(round(res70$beta, 2),length(lm70$residuals))),c(sapply(res70$SE, addParens, 2),"")),
  cbind(paste(c(round(res71$beta, 2),length(lm71$residuals))),c(sapply(res71$SE, addParens, 2),"")),
  cbind(paste(c(round(res72$beta, 2),length(lm72$residuals))),c(sapply(res72$SE, addParens, 2),"")),
  cbind(paste(c(round(res73$beta, 2),length(lm73$residuals))),c(sapply(res73$SE, addParens, 2),"")),
  cbind(paste(c(round(res74$beta, 2),length(lm74$residuals))),c(sapply(res74$SE, addParens, 2),""))
  )
  )

capacity1_print <- data.frame(
                              Outcome = c("Child attendance","",
                                          "Child test score","",
                                          "HH confidence in local instns.","",
                                          "HH perceived teacher quality","",
                                          "HH perceived teacher attendance","",
                                          "CL classroom funds score","",
                                          "Teacher fund application index","",
                                          "Teacher classroom supplies score","",
                                          "Teacher motivation index","",
                                          "Teacher paid regularly",""),
                              Treatment = capacity1_out[,1],
                              CA.sum.score = capacity1_out[,2],
                              Treatment.X.CA.sum.score = capacity1_out[,3],
                              N=capacity1_out[,4])

sink(file="tabs-figs/hh_child_ts_cl_CA_interacted_results.tex")
print(xtable(capacity1_print,
             caption="\\label{tab:CA_interacted_results} Interaction Effects Regressions with Village-Level General Management Capacity Assessment [CA] Sum Scores with Main Child Outcomes and Agency Outcomes for Households, Leaders, and Teachers"),
      include.rownames=F,
      caption.placement = "top",
      hline.after = c(-1,0,seq(2,20, by=2)))
sink()



#########################################################################################
### TABLE A15: VILLAGE-LEVEL PCA SCORES AND MAIN CHILD & AGENCY OUTCOMES 
#########################################################################################

# aged 8-13 attendance outcome with child cov2 list

subset77<-(is.na(eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)'))&(!is.na(dat.hh.ca[,"ros_attend"]))&(!is.na(dat.hh.ca$wt))
y.tr77 <- dat.hh.ca[subset77, "ros_attend"]
XX77<-as.matrix(cbind(dat.hh.ca[subset77, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset77, cov2.child], dm)))
lm77<-lm( formula(paste("y.tr77", "XX77", sep="~")),  weights=dat.hh.ca$wt[subset77])
res77<-coef_test(lm77, vcov=vcovCR(lm77, cluster=dat.hh.ca$CLUSTER[subset77], type="CR2"))
print(res77)

#for supplementary appendix
res77_full<-as.data.frame(res77)

res77<-as.data.frame(res77[2:4,]) # keep second row of output 

# aged 8-13 std_mathread with child cov2 list

subset78<-(is.na(eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)'))&(!is.na(dat.hh.ca[,"std_mathread"]))&(!is.na(dat.hh.ca$wt))
y.tr78 <- dat.hh.ca[subset78, "std_mathread"]
XX78<-as.matrix(cbind(dat.hh.ca[subset78, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset78, cov2.child], dm)))
lm78<-lm( formula(paste("y.tr78", "XX78", sep="~")),  weights=dat.hh.ca$wt[subset78])
res78<-coef_test(lm78, vcov=vcovCR(lm78, cluster=dat.hh.ca$CLUSTER[subset78], type="CR2"))
print(res78)

#for supplementary appendix
res78_full<-as.data.frame(res78)

res78<-as.data.frame(res78[2:4,]) # keep second row of output 

# household, sustainability_confidence_score

subset79<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"sustainability_confidence_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp79<-dat.hh.ca[subset79, "sustainability_confidence_score"]
wms.79<-wtd.mean.sd(y.tmp79[dat.hh.ca$HAND[subset79]==0&dat.hh.ca$TREAT[subset79]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset79])
y.tr79<-(dat.hh.ca[subset79, "sustainability_confidence_score"]-wms.79$mean)/wms.79$sd
XX79<-as.matrix(cbind(dat.hh.ca[subset79, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset79, cov2.hh], dm)))
lm79<-lm( formula(paste("y.tr79", "XX79", sep="~")),  weights=dat.hh.ca$wt[subset79])
res79<-coef_test(lm79, vcov=vcovCR(lm79, cluster=dat.hh.ca$CLUSTER[subset79], type="CR2"))
print(res79)

#for supplementary appendix
res79_full<-as.data.frame(res79)

res79<-as.data.frame(res79[2:4,]) # keep second to fourth row of output 

# household, teacher_perception_score

subset80<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"teacher_perception_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp80<-dat.hh.ca[subset80, "teacher_perception_score"]
wms80<-wtd.mean.sd(y.tmp80[dat.hh.ca$HAND[subset80]==0&dat.hh.ca$TREAT[subset80]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset80])
y.tr80<-(dat.hh.ca[subset80, "teacher_perception_score"]-wms80$mean)/wms80$sd
XX80<-as.matrix(cbind(dat.hh.ca[subset80, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset80, cov2.hh], dm)))
lm80<-lm( formula(paste("y.tr80", "XX80", sep="~")),  weights=dat.hh.ca$wt[subset80])
res80<-coef_test(lm80, vcov=vcovCR(lm80, cluster=dat.hh.ca$CLUSTER[subset80], type="CR2"))
print(res80)

#for supplementary appendix
res80_full<-as.data.frame(res80)

res80<-as.data.frame(res80[2:4,]) # keep second to fourth row of output 

# household, teacher_attend_score

subset81<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"teacher_attend_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp81<-dat.hh.ca[subset81, "teacher_attend_score"]
wms81<-wtd.mean.sd(y.tmp81[dat.hh.ca$HAND[subset81]==0&dat.hh.ca$TREAT[subset81]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset81])
y.tr81<-(dat.hh.ca[subset81, "teacher_attend_score"]-wms81$mean)/wms81$sd
XX81<-as.matrix(cbind(dat.hh.ca[subset81, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset81, cov2.hh], dm)))
lm81<-lm( formula(paste("y.tr81", "XX81", sep="~")),  weights=dat.hh.ca$wt[subset81])
res81<-coef_test(lm81, vcov=vcovCR(lm81, cluster=dat.hh.ca$CLUSTER[subset81], type="CR2"))
print(res81)

#for supplementary appendix
res81_full<-as.data.frame(res81)

res81<-as.data.frame(res81[2:4,]) # keep second row of output 

# CL outcome: classroom funds

subset82<-(is.na(eval(parse(text='(dat.cl.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.ca$TREAT==1)'))&(!is.na(dat.cl.ca[,"cl_funds_supplies_score"]))&(!is.na(dat.cl.ca$wt))
y.tr82<-(dat.cl.ca[subset82, "cl_funds_supplies_score"]-
           mean(dat.cl.ca[subset82&dat.cl.ca$HAND==0, "cl_funds_supplies_score"], na.rm=TRUE))/sd(dat.cl.ca[subset82&dat.cl.ca$HAND==0, "cl_funds_supplies_score"], na.rm=TRUE)
XX82<-as.matrix(cbind(dat.cl.ca[subset82, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], sapply(dat.cl.ca[subset82, cov1.cl], dm)))
lm82<-lm( formula(paste("y.tr82", "XX82", sep="~")),  weights=dat.cl.ca$wt[subset82])
res82<-coef_test(lm82, vcov=vcovCR(lm82, cluster=dat.cl.ca$CLUSTER[subset82], type="CR2"))
print(res82)

#for supplementary appendix
res82_full<-as.data.frame(res82)

res82<-as.data.frame(res82[2:4,]) # keep second row of output 

# Teacher outcome 1: combined fund application index

subset83<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_score.COMBO"]))&(!is.na(dat.ts.ca$wt))
y.tr83<-(dat.ts.ca[subset83, "t_funds_score.COMBO"]-
           mean(dat.ts.ca[subset83&dat.ts.ca$HAND==0, "t_funds_score.COMBO"], na.rm=TRUE))/sd(dat.ts.ca[subset83&dat.ts.ca$HAND==0, "t_funds_score.COMBO"], na.rm=TRUE)
cv83<-dm(dat.ts.ca[subset83, cov1.ts])
XX83<-as.matrix(cbind(dat.ts.ca[subset83, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], cv83))
lm83<-lm( formula(paste("y.tr83", "XX83", sep="~")),  weights=dat.ts.ca$wt[subset83])
res83<-coef_test(lm83, vcov=vcovCR(lm83, cluster=dat.ts.ca$CLUSTER[subset83], type="CR2"))
print(res83)

#for supplementary appendix
res83_full<-as.data.frame(res83)

res83<-as.data.frame(res83[2:4,]) # keep second to fourth row of output 

# Teacher outcome 2: classroom supplies

subset84<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_supplies_score"]))&(!is.na(dat.ts.ca$wt))
y.tr84<-(dat.ts.ca[subset84, "t_funds_supplies_score"]-
           mean(dat.ts.ca[subset84&dat.ts.ca$HAND==0, "t_funds_supplies_score"], na.rm=TRUE))/sd(dat.ts.ca[subset84&dat.ts.ca$HAND==0, "t_funds_supplies_score"], na.rm=TRUE)
cv84<-dm(dat.ts.ca[subset84, cov1.ts])
XX84<-as.matrix(cbind(dat.ts.ca[subset84, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], cv84))
lm84<-lm( formula(paste("y.tr84", "XX84", sep="~")),  weights=dat.ts.ca$wt[subset84])
res84<-coef_test(lm84, vcov=vcovCR(lm84, cluster=dat.ts.ca$CLUSTER[subset84], type="CR2"))
print(res84)

#for supplementary appendix
res84_full<-as.data.frame(res84)

res84<-as.data.frame(res84[2:4,]) # keep second to fourth row of output 

# Teacher outcome 3: combined motivation index

subset85<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_motivation_score.COMBO"]))&(!is.na(dat.ts.ca$wt))
y.tr85<-(dat.ts.ca[subset85, "t_motivation_score.COMBO"]-
           mean(dat.ts.ca[subset85&dat.ts.ca$HAND==0, "t_motivation_score.COMBO"], na.rm=TRUE))/sd(dat.ts.ca[subset85&dat.ts.ca$HAND==0, "t_motivation_score.COMBO"], na.rm=TRUE)
cv85<-dm(dat.ts.ca[subset85, cov1.ts])
XX85<-as.matrix(cbind(dat.ts.ca[subset85, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], cv85))
lm85<-lm( formula(paste("y.tr85", "XX85", sep="~")),  weights=dat.ts.ca$wt[subset85])
res85<-coef_test(lm85, vcov=vcovCR(lm85, cluster=dat.ts.ca$CLUSTER[subset85], type="CR2"))
print(res85)

#for supplementary appendix
res85_full<-as.data.frame(res85)

res85<-as.data.frame(res85[2:4,]) # keep second row of output 

# Teacher outcome 4: teacher paid regularly

subset86<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_regularpay_score"]))&(!is.na(dat.ts.ca$wt))
y.tr86<-(dat.ts.ca[subset86, "t_funds_regularpay_score"]-
           mean(dat.ts.ca[subset86&dat.ts.ca$HAND==0, "t_funds_regularpay_score"], na.rm=TRUE))/sd(dat.ts.ca[subset86&dat.ts.ca$HAND==0, "t_funds_regularpay_score"], na.rm=TRUE)
cv86<-dm(dat.ts.ca[subset86, cov1.ts])
XX86<-as.matrix(cbind(dat.ts.ca[subset86, c("TREAT", "HAND", "p1", "HAND_p1", "HAND_kapisa", "HAND_parwan")], cv86))
lm86<-lm( formula(paste("y.tr86", "XX86", sep="~")),  weights=dat.ts.ca$wt[subset86])
res86<-coef_test(lm86, vcov=vcovCR(lm86, cluster=dat.ts.ca$CLUSTER[subset86], type="CR2"))
print(res86)

#for supplementary appendix
res86_full<-as.data.frame(res86)

res86<-as.data.frame(res86[2:4,]) # keep second to fourth row of output 

capacity2_out <- t(
  cbind(
    cbind(paste(c(round(res77$beta, 2),length(lm77$residuals))),c(sapply(res77$SE, addParens, 2),"")),
    cbind(paste(c(round(res78$beta, 2),length(lm78$residuals))),c(sapply(res78$SE, addParens, 2),"")),
    cbind(paste(c(round(res79$beta, 2),length(lm79$residuals))),c(sapply(res79$SE, addParens, 2),"")),
    cbind(paste(c(round(res80$beta, 2),length(lm80$residuals))),c(sapply(res80$SE, addParens, 2),"")),
    cbind(paste(c(round(res81$beta, 2),length(lm81$residuals))),c(sapply(res81$SE, addParens, 2),"")),
    cbind(paste(c(round(res82$beta, 2),length(lm82$residuals))),c(sapply(res82$SE, addParens, 2),"")),
    cbind(paste(c(round(res83$beta, 2),length(lm83$residuals))),c(sapply(res83$SE, addParens, 2),"")),
    cbind(paste(c(round(res84$beta, 2),length(lm84$residuals))),c(sapply(res84$SE, addParens, 2),"")),
    cbind(paste(c(round(res85$beta, 2),length(lm85$residuals))),c(sapply(res85$SE, addParens, 2),"")),
    cbind(paste(c(round(res86$beta, 2),length(lm86$residuals))),c(sapply(res86$SE, addParens, 2),""))
  )
)

capacity2_print <- data.frame(
  Outcome = c("Child attendance","",
              "Child test score","",
              "HH confidence in local instns.","",
              "HH perceived teacher quality","",
              "HH perceived teacher attendance","",
              "CL classroom funds score","",
              "Teacher fund application index","",
              "Teacher classroom supplies score","",
              "Teacher motivation index","",
              "Teacher paid regularly",""),
  Treatment = capacity2_out[,1],
  CA.PCA.score = capacity2_out[,2],
  Treatment.X.CA.PCA.score = capacity2_out[,3],
  N=capacity2_out[,4])

sink(file="tabs-figs/hh_child_ts_cl_prev_CBofCDC_PCA_results.tex")
print(xtable(capacity2_print,
             caption="\\label{tab:prev_CDC_interacted_results} Interaction Effects Regressions With Village-Level PCA Scores of Previous Capacity Building of CDCs with Main Child Outcomes and Agency Outcomes for Households, Leaders, and Teachers"),
      include.rownames=F,
      caption.placement = "top",
      hline.after = c(-1,0,seq(2,20, by=2)))
sink()

#############################################################################################
### TABLE A16: VILLAGE-LEVEL PCA SCORE of CDC FUNCTIONALITY AND CHILD AND AGENCY OUTCOMES
############################################################################################

# aged 8-13 attendance outcome with child cov2 list

subset89<-(is.na(eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)'))&(!is.na(dat.hh.ca[,"ros_attend"]))&(!is.na(dat.hh.ca$wt))
y.tr89 <- dat.hh.ca[subset89, "ros_attend"]
XX89<-as.matrix(cbind(dat.hh.ca[subset89, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset89, cov2.child], dm)))
lm89<-lm( formula(paste("y.tr89", "XX89", sep="~")),  weights=dat.hh.ca$wt[subset89])
res89<-coef_test(lm89, vcov=vcovCR(lm89, cluster=dat.hh.ca$CLUSTER[subset89], type="CR2"))
print(res89)

#for supplementary appendix
res89_full<-as.data.frame(res89)

res89<-as.data.frame(res89[2:4,]) # keep second row of output 

# aged 8-13 std_mathread with child cov2 list

subset90<-(is.na(eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$ros_age0813==1&dat.hh.ca$TREAT==1)'))&(!is.na(dat.hh.ca[,"std_mathread"]))&(!is.na(dat.hh.ca$wt))
y.tr90 <- dat.hh.ca[subset90, "std_mathread"]
XX90<-as.matrix(cbind(dat.hh.ca[subset90, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset90, cov2.child], dm)))
lm90<-lm( formula(paste("y.tr90", "XX90", sep="~")),  weights=dat.hh.ca$wt[subset90])
res90<-coef_test(lm90, vcov=vcovCR(lm90, cluster=dat.hh.ca$CLUSTER[subset90], type="CR2"))
print(res90)

#for supplementary appendix
res90_full<-as.data.frame(res90)

res90<-as.data.frame(res90[2:4,]) # keep second row of output 

# household, sustainability_confidence_score

subset91<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"sustainability_confidence_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp91<-dat.hh.ca[subset91, "sustainability_confidence_score"]
wms.91<-wtd.mean.sd(y.tmp91[dat.hh.ca$HAND[subset91]==0&dat.hh.ca$TREAT[subset91]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset91])
y.tr91<-(dat.hh.ca[subset91, "sustainability_confidence_score"]-wms.91$mean)/wms.91$sd
XX91<-as.matrix(cbind(dat.hh.ca[subset91, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset91, cov2.hh], dm)))
lm91<-lm( formula(paste("y.tr91", "XX91", sep="~")),  weights=dat.hh.ca$wt[subset91])
res91<-coef_test(lm91, vcov=vcovCR(lm91, cluster=dat.hh.ca$CLUSTER[subset91], type="CR2"))
print(res91)

#for supplementary appendix
res91_full<-as.data.frame(res91)

res91<-as.data.frame(res91[2:4,]) # keep second to fourth row of output 

# household, teacher_perception_score

subset92<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"teacher_perception_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp92<-dat.hh.ca[subset92, "teacher_perception_score"]
wms92<-wtd.mean.sd(y.tmp92[dat.hh.ca$HAND[subset92]==0&dat.hh.ca$TREAT[subset92]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset92])
y.tr92<-(dat.hh.ca[subset92, "teacher_perception_score"]-wms92$mean)/wms92$sd
XX92<-as.matrix(cbind(dat.hh.ca[subset92, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset92, cov2.hh], dm)))
lm92<-lm( formula(paste("y.tr92", "XX92", sep="~")),  weights=dat.hh.ca$wt[subset92])
res92<-coef_test(lm92, vcov=vcovCR(lm92, cluster=dat.hh.ca$CLUSTER[subset92], type="CR2"))
print(res92)

#for supplementary appendix
res92_full<-as.data.frame(res92)

res92<-as.data.frame(res92[2:4,]) # keep second to fourth row of output 

# household, teacher_attend_score

subset93<-(is.na(eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)')))==FALSE)&
  eval(parse(text='(dat.hh.ca$TREAT==1&dat.hh.ca$within.hh.id==1)'))&(!is.na(dat.hh.ca[,"teacher_attend_score"]))&(!is.na(dat.hh.ca$wt))
y.tmp93<-dat.hh.ca[subset93, "teacher_attend_score"]
wms93<-wtd.mean.sd(y.tmp93[dat.hh.ca$HAND[subset93]==0&dat.hh.ca$TREAT[subset93]==1], dat.hh.ca$wt[dat.hh.ca$HAND==0&dat.hh.ca$TREAT==1&subset93])
y.tr93<-(dat.hh.ca[subset93, "teacher_attend_score"]-wms93$mean)/wms93$sd
XX93<-as.matrix(cbind(dat.hh.ca[subset93, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], sapply(dat.hh.ca[subset93, cov2.hh], dm)))
lm93<-lm( formula(paste("y.tr93", "XX93", sep="~")),  weights=dat.hh.ca$wt[subset93])
res93<-coef_test(lm93, vcov=vcovCR(lm93, cluster=dat.hh.ca$CLUSTER[subset93], type="CR2"))
print(res93)

#for supplementary appendix
res93_full<-as.data.frame(res93)

res93<-as.data.frame(res93[2:4,]) # keep second row of output 

# CL outcome: classoom funds

subset94<-(is.na(eval(parse(text='(dat.cl.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.ca$TREAT==1)'))&(!is.na(dat.cl.ca[,"cl_funds_supplies_score"]))&(!is.na(dat.cl.ca$wt))
y.tr94<-(dat.cl.ca[subset94, "cl_funds_supplies_score"]-
           mean(dat.cl.ca[subset94&dat.cl.ca$HAND==0, "cl_funds_supplies_score"], na.rm=TRUE))/sd(dat.cl.ca[subset94&dat.cl.ca$HAND==0, "cl_funds_supplies_score"], na.rm=TRUE)
XX94<-as.matrix(cbind(dat.cl.ca[subset94, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], sapply(dat.cl.ca[subset94, cov1.cl], dm)))
lm94<-lm( formula(paste("y.tr94", "XX94", sep="~")),  weights=dat.cl.ca$wt[subset94])
res94<-coef_test(lm94, vcov=vcovCR(lm94, cluster=dat.cl.ca$CLUSTER[subset94], type="CR2"))
print(res94)

#for supplementary appendix
res94_full<-as.data.frame(res94)

res94<-as.data.frame(res94[2:4,]) # keep second row of output 

# Teacher outcome 1: combined fund application index

subset95<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_score.COMBO"]))&(!is.na(dat.ts.ca$wt))
y.tr95<-(dat.ts.ca[subset95, "t_funds_score.COMBO"]-
           mean(dat.ts.ca[subset95&dat.ts.ca$HAND==0, "t_funds_score.COMBO"], na.rm=TRUE))/sd(dat.ts.ca[subset95&dat.ts.ca$HAND==0, "t_funds_score.COMBO"], na.rm=TRUE)
cv95<-dm(dat.ts.ca[subset95, cov1.ts])
XX95<-as.matrix(cbind(dat.ts.ca[subset95, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], cv95))
lm95<-lm( formula(paste("y.tr95", "XX95", sep="~")),  weights=dat.ts.ca$wt[subset95])
res95<-coef_test(lm95, vcov=vcovCR(lm95, cluster=dat.ts.ca$CLUSTER[subset95], type="CR2"))
print(res95)

#for supplementary appendix
res95_full<-as.data.frame(res95)

res95<-as.data.frame(res95[2:4,]) # keep second to fourth row of output 

# Teacher outcome 2: classroom supplies

subset96<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_supplies_score"]))&(!is.na(dat.ts.ca$wt))
y.tr96<-(dat.ts.ca[subset96, "t_funds_supplies_score"]-
           mean(dat.ts.ca[subset96&dat.ts.ca$HAND==0, "t_funds_supplies_score"], na.rm=TRUE))/sd(dat.ts.ca[subset96&dat.ts.ca$HAND==0, "t_funds_supplies_score"], na.rm=TRUE)
cv96<-dm(dat.ts.ca[subset96, cov1.ts])
XX96<-as.matrix(cbind(dat.ts.ca[subset96, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], cv96))
lm96<-lm( formula(paste("y.tr96", "XX96", sep="~")),  weights=dat.ts.ca$wt[subset96])
res96<-coef_test(lm96, vcov=vcovCR(lm96, cluster=dat.ts.ca$CLUSTER[subset96], type="CR2"))
print(res96)

#for supplementary appendix
res96_full<-as.data.frame(res96)

res96<-as.data.frame(res96[2:4,]) # keep second to fourth row of output 

# Teacher outcome 3: combined motivation index

subset97<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_motivation_score.COMBO"]))&(!is.na(dat.ts.ca$wt))
y.tr97<-(dat.ts.ca[subset97, "t_motivation_score.COMBO"]-
           mean(dat.ts.ca[subset97&dat.ts.ca$HAND==0, "t_motivation_score.COMBO"], na.rm=TRUE))/sd(dat.ts.ca[subset97&dat.ts.ca$HAND==0, "t_motivation_score.COMBO"], na.rm=TRUE)
cv97<-dm(dat.ts.ca[subset97, cov1.ts])
XX97<-as.matrix(cbind(dat.ts.ca[subset97, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], cv97))
lm97<-lm( formula(paste("y.tr97", "XX97", sep="~")),  weights=dat.ts.ca$wt[subset97])
res97<-coef_test(lm97, vcov=vcovCR(lm97, cluster=dat.ts.ca$CLUSTER[subset97], type="CR2"))
print(res97)

#for supplementary appendix
res97_full<-as.data.frame(res97)

res97<-as.data.frame(res97[2:4,]) # keep second row of output 

# Teacher outcome 4: teacher paid regularly

subset98<-(is.na(eval(parse(text='(dat.ts.ca$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts.ca$TREAT==1)'))&(!is.na(dat.ts.ca[,"t_funds_regularpay_score"]))&(!is.na(dat.ts.ca$wt))
y.tr98<-(dat.ts.ca[subset98, "t_funds_regularpay_score"]-
           mean(dat.ts.ca[subset98&dat.ts.ca$HAND==0, "t_funds_regularpay_score"], na.rm=TRUE))/sd(dat.ts.ca[subset98&dat.ts.ca$HAND==0, "t_funds_regularpay_score"], na.rm=TRUE)
cv98<-dm(dat.ts.ca[subset98, cov1.ts])
XX98<-as.matrix(cbind(dat.ts.ca[subset98, c("TREAT", "HAND", "p2", "HAND_p2", "HAND_kapisa", "HAND_parwan")], cv98))
lm98<-lm( formula(paste("y.tr98", "XX98", sep="~")),  weights=dat.ts.ca$wt[subset98])
res98<-coef_test(lm98, vcov=vcovCR(lm98, cluster=dat.ts.ca$CLUSTER[subset98], type="CR2"))
print(res98)

#for supplementary appendix
res98_full<-as.data.frame(res98)

res98<-as.data.frame(res98[2:4,]) # keep second to fourth row of output 


capacity3_out <- t(
  cbind(
    cbind(paste(c(round(res89$beta, 2),length(lm89$residuals))),c(sapply(res89$SE, addParens, 2),"")),
    cbind(paste(c(round(res90$beta, 2),length(lm90$residuals))),c(sapply(res90$SE, addParens, 2),"")),
    cbind(paste(c(round(res91$beta, 2),length(lm91$residuals))),c(sapply(res91$SE, addParens, 2),"")),
    cbind(paste(c(round(res92$beta, 2),length(lm92$residuals))),c(sapply(res92$SE, addParens, 2),"")),
    cbind(paste(c(round(res93$beta, 2),length(lm93$residuals))),c(sapply(res93$SE, addParens, 2),"")),
    cbind(paste(c(round(res94$beta, 2),length(lm94$residuals))),c(sapply(res94$SE, addParens, 2),"")),
    cbind(paste(c(round(res95$beta, 2),length(lm95$residuals))),c(sapply(res95$SE, addParens, 2),"")),
    cbind(paste(c(round(res96$beta, 2),length(lm96$residuals))),c(sapply(res96$SE, addParens, 2),"")),
    cbind(paste(c(round(res97$beta, 2),length(lm97$residuals))),c(sapply(res97$SE, addParens, 2),"")),
    cbind(paste(c(round(res98$beta, 2),length(lm98$residuals))),c(sapply(res98$SE, addParens, 2),""))
  )
)

capacity3_print <- data.frame(
  Outcome = c("Child attendance","",
              "Child test score","",
              "HH confidence in local instns.","",
              "HH perceived teacher quality","",
              "HH perceived teacher attendance","",
              "CL classroom funds score","",
              "Teacher fund application index","",
              "Teacher classroom supplies score","",
              "Teacher motivation index","",
              "Teacher paid regularly",""),
  Treatment = capacity3_out[,1],
  CA.PCA.score = capacity3_out[,2],
  Treatment.X.CA.PCA.score = capacity3_out[,3],
  N=capacity3_out[,4])

sink(file="tabs-figs/hh_child_ts_cl_cdc_functionality_PCA_results.tex")
print(xtable(capacity3_print,
             caption="\\label{tab:CDC_functional_interacted_results} Interaction Effects Regressions With Village-Level PCA Scores of Current CDC Functionality with Main Child Outcomes and Agency Outcomes for Households, Leaders, and Teachers"),
      include.rownames=F,
      caption.placement = "top",
      hline.after = c(-1,0,seq(2,20, by=2)))
sink()


##################################################################################################
### TABLE A17: EFFECTS OF SUSTAINABILITY MODEL ON SUSTAINABILITY PERCEPTIONS 
### OF LEADERS AND TEACHERS
#################################################################################################

# Panel A: Community Leader Survey Sustainability Outcomes

# first index (non-equivalency): cl_sustainability_score.COMBO

subset30<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr30<-(dat.cl[subset30, "cl_sustainability_score.COMBO"]-mean(dat.cl[subset30&dat.cl$HAND==0, "cl_sustainability_score.COMBO"],
                                                                na.rm=TRUE))/sd(dat.cl[subset30&dat.cl$HAND==0, "cl_sustainability_score.COMBO"], na.rm=TRUE)
XX30<-as.matrix(cbind(dat.cl[subset30, c("TREAT", "HAND")], sapply(dat.cl[subset30, cov1.cl], dm)))
lm30<-lm( formula(paste("y.tr30", "XX30", sep="~")),  weights=dat.cl$wt[subset30])
res30<-coef_test(lm30, vcov=vcovCR(lm30, cluster=dat.cl$CLUSTER[subset30], type="CR2"))
print(res30)

#for supplementary appendix
res30_full<-as.data.frame(res30)

res30<-as.data.frame(res30[2,]) # keep second row of output 
res30$N <- length(lm30$residuals)

# second index (non-equivalency): cl_sustainability_future_score

subset31<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr31<-(dat.cl[subset31, "cl_sustainability_future_score"]-mean(dat.cl[subset31&dat.cl$HAND==0, "cl_sustainability_future_score"],
                                                                 na.rm=TRUE))/sd(dat.cl[subset31&dat.cl$HAND==0, "cl_sustainability_future_score"], na.rm=TRUE)
XX31<-as.matrix(cbind(dat.cl[subset31, c("TREAT", "HAND")], sapply(dat.cl[subset31, cov1.cl], dm)))
lm31<-lm( formula(paste("y.tr31", "XX31", sep="~")),  weights=dat.cl$wt[subset31])
res31<-coef_test(lm31, vcov=vcovCR(lm31, cluster=dat.cl$CLUSTER[subset31], type="CR2"))
print(res31)

#for supplementary appendix
res31_full<-as.data.frame(res31)

res31<-as.data.frame(res31[2,]) # keep second row of output 
res31$N <- length(lm31$residuals)

# third index (non-equivalency): cl_sustainability_inst_score

subset32<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr32<-(dat.cl[subset32, "cl_sustainability_inst_score"]-mean(dat.cl[subset32&dat.cl$HAND==0, "cl_sustainability_inst_score"],
                                                               na.rm=TRUE))/sd(dat.cl[subset32&dat.cl$HAND==0, "cl_sustainability_inst_score"], na.rm=TRUE)
XX32<-as.matrix(cbind(dat.cl[subset32, c("TREAT", "HAND")], sapply(dat.cl[subset32, cov1.cl], dm)))
lm32<-lm( formula(paste("y.tr32", "XX32", sep="~")),  weights=dat.cl$wt[subset32])
res32<-coef_test(lm32, vcov=vcovCR(lm32, cluster=dat.cl$CLUSTER[subset32], type="CR2"))
print(res32)

#for supplementary appendix
res32_full<-as.data.frame(res32)

res32<-as.data.frame(res32[2,]) # keep second row of output 
res32$N <- length(lm32$residuals)

# fourth index (non-equivalency): cl_sustainability_classes_score

subset33<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr33<-(dat.cl[subset33, "cl_sustainability_classes_score"]-mean(dat.cl[subset33&dat.cl$HAND==0, "cl_sustainability_classes_score"],
                                                                  na.rm=TRUE))/sd(dat.cl[subset33&dat.cl$HAND==0, "cl_sustainability_classes_score"], na.rm=TRUE)
XX33<-as.matrix(cbind(dat.cl[subset33, c("TREAT", "HAND")], sapply(dat.cl[subset33, cov1.cl], dm)))
lm33<-lm( formula(paste("y.tr33", "XX33", sep="~")),  weights=dat.cl$wt[subset33])
res33<-coef_test(lm33, vcov=vcovCR(lm33, cluster=dat.cl$CLUSTER[subset33], type="CR2"))
print(res33)

#for supplementary appendix
res33_full<-as.data.frame(res33)

res33<-as.data.frame(res33[2,]) # keep second row of output 
res33$N <- length(lm33$residuals)

# fifth index (non-equivalency): cl_sustainability_MOE_score

subset34<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr34<-(dat.cl[subset34, "cl_sustainability_MOE_score"]-mean(dat.cl[subset34&dat.cl$HAND==0, "cl_sustainability_MOE_score"],
                                                              na.rm=TRUE))/sd(dat.cl[subset34&dat.cl$HAND==0, "cl_sustainability_MOE_score"], na.rm=TRUE)
XX34<-as.matrix(cbind(dat.cl[subset34, c("TREAT", "HAND")], sapply(dat.cl[subset34, cov1.cl], dm)))
lm34<-lm( formula(paste("y.tr34", "XX34", sep="~")),  weights=dat.cl$wt[subset34])
res34<-coef_test(lm34, vcov=vcovCR(lm34, cluster=dat.cl$CLUSTER[subset34], type="CR2"))
print(res34)

#for supplementary appendix
res34_full<-as.data.frame(res34)

res34<-as.data.frame(res34[2,]) # keep second row of output 
res34$N <- length(lm34$residuals)

# sixth index (non-equivalency): cl_sustainability_shura_score

subset35<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr35<-(dat.cl[subset35, "cl_sustainability_shura_score"]-mean(dat.cl[subset35&dat.cl$HAND==0, "cl_sustainability_shura_score"],
                                                                na.rm=TRUE))/sd(dat.cl[subset35&dat.cl$HAND==0, "cl_sustainability_shura_score"], na.rm=TRUE)
XX35<-as.matrix(cbind(dat.cl[subset35, c("TREAT", "HAND")], sapply(dat.cl[subset35, cov1.cl], dm)))
lm35<-lm( formula(paste("y.tr35", "XX35", sep="~")),  weights=dat.cl$wt[subset35])
res35<-coef_test(lm35, vcov=vcovCR(lm35, cluster=dat.cl$CLUSTER[subset35], type="CR2"))
print(res35)

#for supplementary appendix
res35_full<-as.data.frame(res35)

res35<-as.data.frame(res35[2,]) # keep second row of output 
res35$N <- length(lm35$residuals)

# Panel B: Teacher Survey Sustainability Outcomes

# first index (non-equivalency): t_sustainability_score.COMBO

subset36<-(is.na(eval(parse(text='(dat.ts$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts$TREAT==1)'))&(!is.na(dat.ts[,"std_t_sustainability_score.COMBO"]))&(!is.na(dat.ts$wt))
y.tr36<-dat.ts[subset36, "std_t_sustainability_score.COMBO"]
cv36<-dm(dat.ts[subset36, cov1.ts])
XX36<-as.matrix(cbind(dat.ts[subset36, c("TREAT", "HAND")], cv36))
lm36<-lm( formula(paste("y.tr36", "XX36", sep="~")),  weights=dat.ts$wt[subset36])
res36<-coef_test(lm36, vcov=vcovCR(lm36, cluster=dat.ts$CLUSTER[subset36], type="CR2"))
print(res36)

#for supplementary appendix
res36_full<-as.data.frame(res36)

res36<-as.data.frame(res36[2,]) # keep second row of output 
res36$N <- length(lm36$residuals)

# second index (non-equivalency): t_sustainability_inst_score

subset37<-(is.na(eval(parse(text='(dat.ts$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts$TREAT==1)'))&(!is.na(dat.ts[,"t_sustainability_inst_score"]))&(!is.na(dat.ts$wt))
y.tr37<-dat.ts[subset37, "t_sustainability_inst_score"]
cv37<-dm(dat.ts[subset37, cov1.ts])
XX37<-as.matrix(cbind(dat.ts[subset37, c("TREAT", "HAND")], cv37))
lm37<-lm( formula(paste("y.tr37", "XX37", sep="~")),  weights=dat.ts$wt[subset37])
res37<-coef_test(lm37, vcov=vcovCR(lm37, cluster=dat.ts$CLUSTER[subset37], type="CR2"))
print(res37)

#for supplementary appendix
res37_full<-as.data.frame(res37)

res37<-as.data.frame(res37[2,]) # keep second row of output 
res37$N <- length(lm37$residuals)

# fourth index (non-equivalency): t_sustainability_school_score

subset38<-(is.na(eval(parse(text='(dat.ts$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts$TREAT==1)'))&(!is.na(dat.ts[,"t_sustainability_school_score"]))&(!is.na(dat.ts$wt))
y.tr38<-dat.ts[subset38, "t_sustainability_school_score"]
cv38<-dm(dat.ts[subset38, cov1.ts])
XX38<-as.matrix(cbind(dat.ts[subset38, c("TREAT", "HAND")], cv38))
lm38<-lm( formula(paste("y.tr38", "XX38", sep="~")),  weights=dat.ts$wt[subset38])
res38<-coef_test(lm38, vcov=vcovCR(lm38, cluster=dat.ts$CLUSTER[subset38], type="CR2"))
print(res38)

#for supplementary appendix
res38_full<-as.data.frame(res38)

res38<-as.data.frame(res38[2,]) # keep second row of output 
res38$N <- length(lm38$residuals)

# fifth index (non-equivalency): t_sustainability_MOE_score

subset39<-(is.na(eval(parse(text='(dat.ts$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts$TREAT==1)'))&(!is.na(dat.ts[,"t_sustainability_MOE_score"]))&(!is.na(dat.ts$wt))
y.tr39<-(dat.ts[subset39, "t_sustainability_MOE_score"]-
           mean(dat.ts[subset39&dat.ts$HAND==0, "t_sustainability_MOE_score"], na.rm=TRUE))/sd(dat.ts[subset39&dat.ts$HAND==0, "t_sustainability_MOE_score"], na.rm=TRUE)
cv39<-dm(dat.ts[subset39, cov1.ts])
XX39<-as.matrix(cbind(dat.ts[subset39, c("TREAT", "HAND")], cv39))
lm39<-lm( formula(paste("y.tr39", "XX39", sep="~")),  weights=dat.ts$wt[subset39])
res39<-coef_test(lm39, vcov=vcovCR(lm39, cluster=dat.ts$CLUSTER[subset39], type="CR2"))
print(res39)

#for supplementary appendix
res39_full<-as.data.frame(res39)

res39<-as.data.frame(res39[2,]) # keep second row of output 
res39$N <- length(lm39$residuals)

# sixth index (non-equivalency): std_t_sustainability_shura_score

subset40<-(is.na(eval(parse(text='(dat.ts$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts$TREAT==1)'))&(!is.na(dat.ts[,"std_t_sustainability_shura_score"]))&(!is.na(dat.ts$wt))
y.tr40<-dat.ts[subset40, "std_t_sustainability_shura_score"]
cv40<-dm(dat.ts[subset40, cov1.ts])
XX40<-as.matrix(cbind(dat.ts[subset40, c("TREAT", "HAND")], cv40))
lm40<-lm( formula(paste("y.tr40", "XX40", sep="~")),  weights=dat.ts$wt[subset40])
res40<-coef_test(lm40, vcov=vcovCR(lm40, cluster=dat.ts$CLUSTER[subset40], type="CR2"))
print(res40)

#for supplementary appendix
res40_full<-as.data.frame(res40)

res40<-as.data.frame(res40[2,]) # keep second row of output 
res40$N <- length(lm40$residuals)

# seventh index (non-equivalency): t_sustainability_teacher_score

subset41<-(is.na(eval(parse(text='(dat.ts$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.ts$TREAT==1)'))&(!is.na(dat.ts[,"t_sustainability_teacher_score"]))&(!is.na(dat.ts$wt))
y.tr41<-(dat.ts[subset41, "t_sustainability_teacher_score"]-
           mean(dat.ts[subset41&dat.ts$HAND==0, "t_sustainability_teacher_score"], na.rm=TRUE))/sd(dat.ts[subset41&dat.ts$HAND==0, "t_sustainability_teacher_score"], na.rm=TRUE)
cv41<-dm(dat.ts[subset41, cov1.ts])
XX41<-as.matrix(cbind(dat.ts[subset41, c("TREAT", "HAND")], cv41))
lm41<-lm( formula(paste("y.tr41", "XX41", sep="~")),  weights=dat.ts$wt[subset41])
res41<-coef_test(lm41, vcov=vcovCR(lm41, cluster=dat.ts$CLUSTER[subset41], type="CR2"))
print(res41)

#for supplementary appendix
res41_full<-as.data.frame(res41)

res41<-as.data.frame(res41[2,]) # keep second row of output 
res41$N <- length(lm41$residuals)

Table13_Output<-rbind(res30, res31, res32, res33, res34, res35, 
                      res36, res37, res38, res39, res40, res41)

Table13_print <- data.frame(Sample = c("Panel A: Community Leaders", rep("",5),
                                       "Panel B: Teachers", rep("",5)),
                            Outcome = c("Combined sustainability index", 
                                        "Community provision for future classes", 
                                        "Confidence in community institutions",
                                        "Confidence that school will be sustained",
                                        "MOE provisions for funding teachers",
                                        "Shura provisions for future classes",
                                        "Combined sustainability index",
                                        "Confidence in local community institutions",
                                        "Confidence that school will be sustained.", 
                                        "Proactive management from.MOE",
                                        "Proactive management from.shuras",
                                        "Teacher plans to remain CBE teacher"),
                            Treatment.Effect = round(Table13_Output$beta, 2),
                            Std.Error = addParens(round(Table13_Output$SE, 2),2),
                            p.value = round(Table13_Output$p_Satt, 2),
                            N=Table13_Output$N)

sink(file="tabs-figs/cl_ts_sustainability_endline_results.tex")
print(
xtable(Table13_print,
       caption= "\\label{tab:endline_sustainability} Effects of Sustainability Model on Sustainability Outcomes for Teachers and Community Leaders"),
caption.placement = "top",
hline.after = c(-1,0,6,12),
include.rownames = FALSE
)
sink()

##################################################################
### TABLE A18: HETEROGENEOUS TREATMENT EFFECTS BY IMPLEMENTING NGO
##################################################################

children_dat$CRS <- 1*(children_dat$NGO==2)
within_hh_dat$CRS <- 1*(within_hh_dat$NGO==2)
children_dat$CRSXHAND <- children_dat$CRS*children_dat$HAND
within_hh_dat$CRSXHAND <- within_hh_dat$CRS*within_hh_dat$HAND

XX_children_CRS <-as.matrix(cbind(children_dat[, c("TREAT", "HAND","CRS","CRSXHAND")], sapply(children_dat[, cov2.child], dm)))
XX_hh_CRS <-as.matrix(cbind(within_hh_dat[, c("TREAT", "HAND","CRS","CRSXHAND")], sapply(within_hh_dat[, cov2.hh], dm)))


y.tr1.crs <- children_dat$ros_attend
lm1.crs<-lm( formula(paste("y.tr1.crs", "XX_children_CRS", sep="~")),  weights=children_dat$wt)

#full covariate output for supplementary appendix
res1.crs_full<-as.data.frame(coef_test(lm1.crs, vcov=vcovCR(lm1.crs, cluster=children_dat$CLUSTER, type="CR2")))

res1.crs<-as.data.frame(coef_test(lm1.crs, vcov=vcovCR(lm1.crs, cluster=children_dat$CLUSTER, type="CR2")))[2:4,]

y.tr2.crs <- children_dat[, "std_mathread"]
lm2.crs<-lm(formula(paste("y.tr2.crs", "XX_children_CRS", sep="~")),  weights=children_dat$wt)

#full covariate output for supplementary appendix
res2.crs_full<-as.data.frame(coef_test(lm2.crs, vcov=vcovCR(lm2.crs, cluster=children_dat$CLUSTER, type="CR2")))

res2.crs<-as.data.frame(coef_test(lm2.crs, vcov=vcovCR(lm2.crs, cluster=children_dat$CLUSTER, type="CR2")))[2:4,]

y.tr3.crs <- within_hh_dat$std_satisfaction_access_score
lm3.crs<-lm( formula(paste("y.tr3.crs", "XX_hh_CRS", sep="~")),  weights=within_hh_dat$wt)

#full covariate output for supplementary appendix
res3.crs_full<-as.data.frame(coef_test(lm3.crs, vcov=vcovCR(lm3.crs, cluster=within_hh_dat$CLUSTER, type="CR2")))

res3.crs<-as.data.frame(coef_test(lm3.crs, vcov=vcovCR(lm3.crs, cluster=within_hh_dat$CLUSTER, type="CR2")))[2:4,]

Table14_Output <- rbind(
c(paste(round(res1.crs$beta, 2)), paste(round(res1.crs$p_Satt[3], 2)),paste(length(lm1.crs$residuals))),
c(addParens(res1.crs$SE, 2),"",""),
c(paste(round(res2.crs$beta, 2)), paste(round(res2.crs$p_Satt[3], 2)),paste(length(lm2.crs$residuals))),
c(addParens(res2.crs$SE, 2),"",""),
c(paste(round(res3.crs$beta, 2)), paste(round(res3.crs$p_Satt[3], 2)),paste(length(lm3.crs$residuals))),
c(addParens(res3.crs$SE, 2),"","")
)

Table14_Print <- data.frame(Outcome = c("Children's attendance","",
                                        "Children's test scores","",
                                        "Household satisfaction",""),
                            Treatment = Table14_Output[,1],
                            CRS = Table14_Output[,2],
                            TreatmentXCRS = Table14_Output[,3],
                            Interaction.term.p.value  = Table14_Output[,4],
                            N = Table14_Output[,5]
                            )
sink(file="tabs-figs/NGO_htes.tex")
print(
xtable(Table14_Print,
       caption = "\\label{tab:NGO_hte} Heterogeneous Treatment Effects by Implementing NGO"),
caption.placement = "top",
hline.after = c(-1,0,2,4,6),
include.rownames = FALSE
)
sink()

##################################################################################################
### TABLE A19: COMMUNITY LEADERS' LONGER-TERM PERCEPTIONS OF CBE SUSTAINABILITY (CARE AND CRS)
#################################################################################################

# index tested under equivalency hypothesis  
subset42<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))

# phone_sustain_want_score_std is false on binary outcome and standardize false, thus:

y.tr42<-dat.cl[subset42, "phone_sustain_want_score_rev"]

# ordering of covariate list seems to matter 
XX42<-as.matrix(cbind(dat.cl[subset42, c("TREAT", "HAND")], sapply(dat.cl[subset42, cov1.cl], dm)))

lm42<-lm( formula(paste("y.tr42", "XX42", sep="~")),  weights=dat.cl$wt[subset42])
res42<-coef_test(lm42, vcov=vcovCR(lm42, cluster=dat.cl$CLUSTER[subset42], type="CR2"))
print(res42)

#full results for supplementary appendix
res42_full<-as.data.frame(res42) 

res42<-as.data.frame(res42[2,]) # keep second row of output 
res42$N <- length(lm42$residuals)

# indexes tested under non-equivalency hypothesis  

# first index: sustain.index_std

subset43<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))

# sustain.index_std is false on binary outcome and standardize false, thus:

y.tr43<-dat.cl[subset43, "sustain.index_std"]

# ordering of covariate list seems to matter 
XX43<-as.matrix(cbind(dat.cl[subset43, c("TREAT", "HAND")], sapply(dat.cl[subset43, cov1.cl], dm)))

lm43<-lm( formula(paste("y.tr43", "XX43", sep="~")),  weights=dat.cl$wt[subset43])
res43<-coef_test(lm43, vcov=vcovCR(lm43, cluster=dat.cl$CLUSTER[subset43], type="CR2"))
print(res43)

#full results for supplementary appendix
res43_full<-as.data.frame(res43) 

res43<-as.data.frame(res43[2,]) # keep second row of output 
res43$N <- length(lm43$residuals)

# second index: phone_sustain_initiative_score_std

subset44<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))

# phone_sustain_initiative_score_std is false on binary outcome and standardize false, thus:

y.tr44<-dat.cl[subset44, "phone_sustain_initiative_score_std"]

# ordering of covariate list seems to matter 
XX44<-as.matrix(cbind(dat.cl[subset44, c("TREAT", "HAND")], sapply(dat.cl[subset44, cov1.cl], dm)))

lm44<-lm( formula(paste("y.tr44", "XX44", sep="~")),  weights=dat.cl$wt[subset44])
res44<-coef_test(lm44, vcov=vcovCR(lm44, cluster=dat.cl$CLUSTER[subset44], type="CR2"))
print(res44)

#full results for supplementary appendix
res44_full<-as.data.frame(res44) 

res44<-as.data.frame(res44[2,]) # keep second row of output 
res44$N <- length(lm44$residuals)

# third index: phone_sustain_provisions_score_std

subset45<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))

# phone_sustain_initiative_score_std is false on binary outcome and standardize false, thus:

y.tr45<-dat.cl[subset45, "phone_sustain_provisions_score_std"]

# ordering of covariate list seems to matter 
XX45<-as.matrix(cbind(dat.cl[subset45, c("TREAT", "HAND")], sapply(dat.cl[subset45, cov1.cl], dm)))

lm45<-lm( formula(paste("y.tr45", "XX45", sep="~")),  weights=dat.cl$wt[subset45])
res45<-coef_test(lm45, vcov=vcovCR(lm45, cluster=dat.cl$CLUSTER[subset45], type="CR2"))
print(res45)

#full results for supplementary appendix
res45_full<-as.data.frame(res45) 

res45<-as.data.frame(res45[2,]) # keep second row of output 
res45$N <- length(lm45$residuals)

# fourth index: phone_sustain_confidence_score

subset46<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))

# phone_sustain_confidence_score is false on binary outcome and standardize false, thus:

y.tr46<-dat.cl[subset46, "phone_sustain_confidence_score"]

# ordering of covariate list seems to matter 
XX46<-as.matrix(cbind(dat.cl[subset46, c("TREAT", "HAND")], sapply(dat.cl[subset46, cov1.cl], dm)))

lm46<-lm( formula(paste("y.tr46", "XX46", sep="~")),  weights=dat.cl$wt[subset46])
res46<-coef_test(lm46, vcov=vcovCR(lm46, cluster=dat.cl$CLUSTER[subset46], type="CR2"))
print(res46)

#full results for supplementary appendix
res46_full<-as.data.frame(res46) 

res46<-as.data.frame(res46[2,]) # keep second row of output 
res46$N <- length(lm46$residuals)

# fifth index: phone_sustain_2018_score

subset47<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))

# phone_sustain_2018_score is false on binary outcome and standardize false, thus:

y.tr47<-dat.cl[subset47, "phone_sustain_2018_score"]

# ordering of covariate list seems to matter 
XX47<-as.matrix(cbind(dat.cl[subset47, c("TREAT", "HAND")], sapply(dat.cl[subset47, cov1.cl], dm)))

lm47<-lm( formula(paste("y.tr47", "XX47", sep="~")),  weights=dat.cl$wt[subset47])
res47<-coef_test(lm47, vcov=vcovCR(lm47, cluster=dat.cl$CLUSTER[subset47], type="CR2"))
print(res47)

#full results for supplementary appendix
res47_full<-as.data.frame(res47) 

res47<-as.data.frame(res47[2,]) # keep second row of output 
res47$N <- length(lm47$residuals)

Table15_Output<-rbind(res42, res43, res44, res45, res46, res47)

Table15_format <- data.frame(Treatment.Effect = round(Table15_Output$beta, 2),
                              Std.Err. = sapply(round(Table15_Output$SE, 2),
                                              function(x) {paste0("(",x,")")}),
                              N = Table15_Output$N)



rownames(Table15_format) <- rownames(Table2_sum)

Table15_print<-xtable(Table15_format,
                     caption="\\label{tab:follow_up}Community Leaders' Longer-term Perceptions of CBE Sustainability (CARE and CRS Samples)")

addtorow <- list()
addtorow$pos <- list(0,1,1)
addtorow$command <- c("{\\bf Equivalency Outcome}  &  &  &  & &  & &\\\\\n",
                      "\\\\\n",
                      "{\\bf Non-Equivalency Outcomes}  &  &  &  & &  & & \\\\\n")
sink(file="tabs-figs/cl_follow_up_sustainability_full_sample.tex")
print(Table15_print, 
      add.to.row = addtorow,
      caption.placement = "top",
      hline.after = -1)
sink()


###############################################################################
### TABLE A20: INTERACTION EFFECT OF CL AGE AND EDUC FOR ENDLINE SUSTAINABILITY OUTCOMES
##############################################################################

#############################################################
#Age-conditional effects on end-line sustainability outcomes
#############################################################

# set up variable for older and younger community leaders based on median age
median(dat.cl$hhhead_age) #52.3125

#binary indicator for leaders who are <52 and those >=52
dat.cl$older_leader <- ifelse(dat.cl$hhhead_age>=52, 1, 0)

#create interaction variable to add to covariate list 
dat.cl$HAND_age<-dat.cl$HAND*dat.cl$older_leader

#combined sustainability index

subset48<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr48<-(dat.cl[subset48, "cl_sustainability_score.COMBO"]-mean(dat.cl[subset48&dat.cl$HAND==0, "cl_sustainability_score.COMBO"],
                                                                na.rm=TRUE))/sd(dat.cl[subset48&dat.cl$HAND==0, "cl_sustainability_score.COMBO"], na.rm=TRUE)
XX48<-as.matrix(cbind(dat.cl[subset48, c("TREAT", "HAND", "older_leader", "HAND_age")], sapply(dat.cl[subset48, cov1.cl], dm)))
lm48<-lm( formula(paste("y.tr48", "XX48", sep="~")),  weights=dat.cl$wt[subset48])
res48<-coef_test(lm48, vcov=vcovCR(lm48, cluster=dat.cl$CLUSTER[subset48], type="CR2"))

#full regression output for supplementary appendix
res48_full<-as.data.frame(res48) 

res48<-as.data.frame(res48[2:4,]) 

#community provision for future classes

subset48b<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr48b<-(dat.cl[subset48b, "cl_sustainability_future_score"]-mean(dat.cl[subset48b&dat.cl$HAND==0, "cl_sustainability_future_score"],
                                                                   na.rm=TRUE))/sd(dat.cl[subset48b&dat.cl$HAND==0, "cl_sustainability_future_score"], na.rm=TRUE)
XX48b<-as.matrix(cbind(dat.cl[subset48b, c("TREAT", "HAND", "older_leader", "HAND_age")], sapply(dat.cl[subset48b, cov1.cl], dm)))
lm48b<-lm( formula(paste("y.tr48b", "XX48b", sep="~")),  weights=dat.cl$wt[subset48b])
res48b<-coef_test(lm48b, vcov=vcovCR(lm48b, cluster=dat.cl$CLUSTER[subset48b], type="CR2"))

#full regression output for supplementary appendix
res48b_full<-as.data.frame(res48b) 

res48b<-as.data.frame(res48b[2:4,]) 

#confidence in local community institutions

subset48c<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr48c<-(dat.cl[subset48c, "cl_sustainability_inst_score"]-mean(dat.cl[subset48c&dat.cl$HAND==0, "cl_sustainability_inst_score"],
                                                                 na.rm=TRUE))/sd(dat.cl[subset48c&dat.cl$HAND==0, "cl_sustainability_inst_score"], na.rm=TRUE)
XX48c<-as.matrix(cbind(dat.cl[subset48c, c("TREAT", "HAND", "older_leader", "HAND_age")], sapply(dat.cl[subset48c, cov1.cl], dm)))
lm48c<-lm( formula(paste("y.tr48c", "XX48c", sep="~")),  weights=dat.cl$wt[subset48c])
res48c<-coef_test(lm48c, vcov=vcovCR(lm48c, cluster=dat.cl$CLUSTER[subset48c], type="CR2"))

#full regression output for supplementary appendix
res48c_full<-as.data.frame(res48c) 

res48c<-as.data.frame(res48c[2:4,]) 

#confidence that school will be sustained

subset48d<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr48d<-(dat.cl[subset48d, "cl_sustainability_classes_score"]-mean(dat.cl[subset48d&dat.cl$HAND==0, "cl_sustainability_classes_score"],
                                                                    na.rm=TRUE))/sd(dat.cl[subset48d&dat.cl$HAND==0, "cl_sustainability_classes_score"], na.rm=TRUE)
XX48d<-as.matrix(cbind(dat.cl[subset48d, c("TREAT", "HAND", "older_leader", "HAND_age")], sapply(dat.cl[subset48d, cov1.cl], dm)))
lm48d<-lm( formula(paste("y.tr48d", "XX48d", sep="~")),  weights=dat.cl$wt[subset48d])
res48d<-coef_test(lm48d, vcov=vcovCR(lm48d, cluster=dat.cl$CLUSTER[subset48d], type="CR2"))

#full regression output for supplementary appendix
res48d_full<-as.data.frame(res48d) 

res48d<-as.data.frame(res48d[2:4,]) 

#MoE provisions for future funding

subset48e<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr48e<-(dat.cl[subset48e, "cl_sustainability_MOE_score"]-mean(dat.cl[subset48e&dat.cl$HAND==0, "cl_sustainability_MOE_score"],
                                                                na.rm=TRUE))/sd(dat.cl[subset48e&dat.cl$HAND==0, "cl_sustainability_MOE_score"], na.rm=TRUE)
XX48e<-as.matrix(cbind(dat.cl[subset48e, c("TREAT", "HAND", "older_leader", "HAND_age")], sapply(dat.cl[subset48e, cov1.cl], dm)))
lm48e<-lm( formula(paste("y.tr48e", "XX48e", sep="~")),  weights=dat.cl$wt[subset48e])
res48e<-coef_test(lm48e, vcov=vcovCR(lm48e, cluster=dat.cl$CLUSTER[subset48e], type="CR2"))

#full regression output for supplementary appendix
res48e_full<-as.data.frame(res48e) 

res48e<-as.data.frame(res48e[2:4,]) 

#Shura provisions for future classes

subset48f<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr48f<-(dat.cl[subset48f, "cl_sustainability_shura_score"]-mean(dat.cl[subset48f&dat.cl$HAND==0, "cl_sustainability_shura_score"],
                                                                  na.rm=TRUE))/sd(dat.cl[subset48f&dat.cl$HAND==0, "cl_sustainability_shura_score"], na.rm=TRUE)
XX48f<-as.matrix(cbind(dat.cl[subset48f, c("TREAT", "HAND", "older_leader", "HAND_age")], sapply(dat.cl[subset48f, cov1.cl], dm)))
lm48f<-lm( formula(paste("y.tr48f", "XX48f", sep="~")),  weights=dat.cl$wt[subset48f])
res48f<-coef_test(lm48f, vcov=vcovCR(lm48f, cluster=dat.cl$CLUSTER[subset48f], type="CR2"))

#full regression output for supplementary appendix
res48f_full<-as.data.frame(res48f) 

res48f<-as.data.frame(res48f[2:4,]) 


cl_age <- t(
  cbind(
    cbind(paste(c(round(res48$beta, 2),length(lm48$residuals))),c(sapply(res48$SE, addParens, 2),"")),
    cbind(paste(c(round(res48b$beta, 2),length(lm48b$residuals))),c(sapply(res48b$SE, addParens, 2),"")),
    cbind(paste(c(round(res48c$beta, 2),length(lm48c$residuals))),c(sapply(res48c$SE, addParens, 2),"")),
    cbind(paste(c(round(res48d$beta, 2),length(lm48d$residuals))),c(sapply(res48d$SE, addParens, 2),"")),
    cbind(paste(c(round(res48e$beta, 2),length(lm48e$residuals))),c(sapply(res48e$SE, addParens, 2),"")),
    cbind(paste(c(round(res48f$beta, 2),length(lm48f$residuals))),c(sapply(res48f$SE, addParens, 2),""))
  )
)

cl_age_print <- data.frame(
  Outcome = c("Combined sustainability index","",
              "Community provision for future classes","",
              "Confidence in community institutions","",
              "Confidence that school will be sustained","",
              "MOE provisions for funding teachers","",
              "Shura provisions for future classes",""),
  Treatment = cl_age[,1],
  Older.leader = cl_age[,2],
  Treatment.X.Older.leader = cl_age[,3],
  N=cl_age[,4])

################################################################
#Educ-conditional effects on end-line sustainability outcomes
################################################################

#create interaction variable to add to covariate list 
dat.cl$HAND_educ<-dat.cl$HAND*dat.cl$educ

#first index: cl_sustainability_score.COMBO

subset49<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr49<-(dat.cl[subset49, "cl_sustainability_score.COMBO"]-mean(dat.cl[subset49&dat.cl$HAND==0, "cl_sustainability_score.COMBO"],
                                                                na.rm=TRUE))/sd(dat.cl[subset49&dat.cl$HAND==0, "cl_sustainability_score.COMBO"], na.rm=TRUE)
XX49<-as.matrix(cbind(dat.cl[subset49, c("TREAT", "HAND", "educ", "HAND_educ")], sapply(dat.cl[subset49, cov1.cl], dm)))
lm49<-lm( formula(paste("y.tr49", "XX49", sep="~")),  weights=dat.cl$wt[subset49])
res49<-coef_test(lm49, vcov=vcovCR(lm49, cluster=dat.cl$CLUSTER[subset49], type="CR2"))

#full regression output for supplementary appendix
res49_full<-as.data.frame(res49) 

res49<-as.data.frame(res49[2:4,]) 

# second index (non-equivalency): cl_sustainability_future_score

subset49b<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr49b<-(dat.cl[subset49b, "cl_sustainability_future_score"]-mean(dat.cl[subset49b&dat.cl$HAND==0, "cl_sustainability_future_score"],
                                                                   na.rm=TRUE))/sd(dat.cl[subset49b&dat.cl$HAND==0, "cl_sustainability_future_score"], na.rm=TRUE)
XX49b<-as.matrix(cbind(dat.cl[subset49b, c("TREAT", "HAND", "educ", "HAND_educ")], sapply(dat.cl[subset49b, cov1.cl], dm)))
lm49b<-lm( formula(paste("y.tr49b", "XX49b", sep="~")),  weights=dat.cl$wt[subset49b])
res49b<-coef_test(lm49b, vcov=vcovCR(lm49b, cluster=dat.cl$CLUSTER[subset49b], type="CR2"))

#full regression output for supplementary appendix
res49b_full<-as.data.frame(res49b) 

res49b<-as.data.frame(res49b[2:4,]) 

# third index (non-equivalency): cl_sustainability_inst_score

subset49c<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr49c<-(dat.cl[subset49c, "cl_sustainability_inst_score"]-mean(dat.cl[subset49c&dat.cl$HAND==0, "cl_sustainability_inst_score"],
                                                                 na.rm=TRUE))/sd(dat.cl[subset49c&dat.cl$HAND==0, "cl_sustainability_inst_score"], na.rm=TRUE)
XX49c<-as.matrix(cbind(dat.cl[subset49c, c("TREAT", "HAND", "educ", "HAND_educ")], sapply(dat.cl[subset49c, cov1.cl], dm)))
lm49c<-lm( formula(paste("y.tr49c", "XX49c", sep="~")),  weights=dat.cl$wt[subset49c])
res49c<-coef_test(lm49c, vcov=vcovCR(lm49c, cluster=dat.cl$CLUSTER[subset49c], type="CR2"))

#full regression output for supplementary appendix
res49c_full<-as.data.frame(res49c) 

res49c<-as.data.frame(res49c[2:4,]) 

# fourth index (non-equivalency): cl_sustainability_classes_score

subset49d<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr49d<-(dat.cl[subset49d, "cl_sustainability_classes_score"]-mean(dat.cl[subset49d&dat.cl$HAND==0, "cl_sustainability_classes_score"],
                                                                    na.rm=TRUE))/sd(dat.cl[subset49d&dat.cl$HAND==0, "cl_sustainability_classes_score"], na.rm=TRUE)
XX49d<-as.matrix(cbind(dat.cl[subset49d, c("TREAT", "HAND", "educ", "HAND_educ")], sapply(dat.cl[subset49d, cov1.cl], dm)))
lm49d<-lm( formula(paste("y.tr49d", "XX49d", sep="~")),  weights=dat.cl$wt[subset49d])
res49d<-coef_test(lm49d, vcov=vcovCR(lm49d, cluster=dat.cl$CLUSTER[subset49d], type="CR2"))

#full regression output for supplementary appendix
res49d_full<-as.data.frame(res49d) 

res49d<-as.data.frame(res49d[2:4,]) 

# fifth index (non-equivalency): cl_sustainability_MOE_score

subset49e<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr49e<-(dat.cl[subset49e, "cl_sustainability_MOE_score"]-mean(dat.cl[subset49e&dat.cl$HAND==0, "cl_sustainability_MOE_score"],
                                                                na.rm=TRUE))/sd(dat.cl[subset49e&dat.cl$HAND==0, "cl_sustainability_MOE_score"], na.rm=TRUE)
XX49e<-as.matrix(cbind(dat.cl[subset48e, c("TREAT", "HAND", "educ", "HAND_educ")], sapply(dat.cl[subset49e, cov1.cl], dm)))
lm49e<-lm( formula(paste("y.tr49e", "XX49e", sep="~")),  weights=dat.cl$wt[subset49e])
res49e<-coef_test(lm49e, vcov=vcovCR(lm49e, cluster=dat.cl$CLUSTER[subset49e], type="CR2"))

#full regression output for supplementary appendix
res49e_full<-as.data.frame(res49e) 

res49e<-as.data.frame(res49e[2:4,]) 

# sixth index (non-equivalency): cl_sustainability_shura_score

subset49f<-(is.na(eval(parse(text='(dat.cl$TREAT==1)')))==FALSE)&eval(parse(text='(dat.cl$TREAT==1)'))
y.tr49f<-(dat.cl[subset48f, "cl_sustainability_shura_score"]-mean(dat.cl[subset49f&dat.cl$HAND==0, "cl_sustainability_shura_score"],
                                                                  na.rm=TRUE))/sd(dat.cl[subset49f&dat.cl$HAND==0, "cl_sustainability_shura_score"], na.rm=TRUE)
XX49f<-as.matrix(cbind(dat.cl[subset49f, c("TREAT", "HAND", "educ", "HAND_educ")], sapply(dat.cl[subset49f, cov1.cl], dm)))
lm49f<-lm( formula(paste("y.tr49f", "XX49f", sep="~")),  weights=dat.cl$wt[subset49f])
res49f<-coef_test(lm49f, vcov=vcovCR(lm49f, cluster=dat.cl$CLUSTER[subset49f], type="CR2"))

#full regression output for supplementary appendix
res49f_full<-as.data.frame(res49f) 

res49f<-as.data.frame(res49f[2:4,]) 

cl_edu <- t(
  cbind(
    cbind(paste(c(round(res49$beta, 2),length(lm49$residuals))),c(sapply(res49$SE, addParens, 2),"")),
    cbind(paste(c(round(res49b$beta, 2),length(lm49b$residuals))),c(sapply(res49b$SE, addParens, 2),"")),
    cbind(paste(c(round(res49c$beta, 2),length(lm49c$residuals))),c(sapply(res49c$SE, addParens, 2),"")),
    cbind(paste(c(round(res49d$beta, 2),length(lm49d$residuals))),c(sapply(res49d$SE, addParens, 2),"")),
    cbind(paste(c(round(res49e$beta, 2),length(lm49e$residuals))),c(sapply(res49e$SE, addParens, 2),"")),
    cbind(paste(c(round(res49f$beta, 2),length(lm49f$residuals))),c(sapply(res49f$SE, addParens, 2),""))
  )
)

cl_edu_print <- data.frame(
  Outcome = c("Combined sustainability index","",
              "Community provision for future classes","",
              "Confidence in community institutions","",
              "Confidence that school will be sustained","",
              "MOE provisions for funding teachers","",
              "Shura provisions for future classes",""),
  Treatment = cl_edu[,1],
  Educated.leader = cl_edu[,2],
  Treatment.X.Educated.leader = cl_edu[,3],
  N=cl_edu[,4])


sink(file="tabs-figs/cl_age_educ_endline_interactions.tex")
print(xtable(cl_age_print,
             caption="\\label{tab:CL_interacted_age_educ_endline} Interaction Effect Regressions With Community Leaders' Age and Educational Status, Endline Sustainability Outcomes"),
      include.rownames=F,
      caption.placement = "top")
print(xtable(cl_edu_print),
      include.rownames=F,
      caption.placement = "top")
mean(dat.cl$educ)
sink()

##################################################################################################
### TABLE A20: CORR off CL PERCEPTIONS OF SUCCESS OF INTERVENTION WITH ACTUAL CHILDREN PERFORMANCE
##################################################################################################

dat.cl.child<-read.dta13("wave4_merged_CL_child_scores.dta")

dat.cl.child$PROVINCE1<-1*(dat.cl.child$Province=="Parwan")
dat.cl.child$PROVINCE2<-1*(dat.cl.child$Province=="Kapisa")
dat.cl.child$PROVINCE3<-1*(dat.cl.child$Province=="Herat")
dat.cl.child$PROVINCE4<-1*(dat.cl.child$Province=="Bamian")
dat.cl.child$PROVINCE5<-1*(dat.cl.child$Province=="Ghur")
dat.cl.child$PROVINCE6<-1*(dat.cl.child$Province=="Dykundi")

#assign village size variable to dat
dat.cl.child$num_hh_needsassmnt<-vil.sizes[dat.cl.child$VUID,]$num_hh_needsassmnt
dat.cl.child$ss_wt<-1
dat.cl.child$wt<-1

# constructing additional outcomes

dat.cl.child$TREAT<-(dat.cl.child$TCode>0)*1
dat.cl.child$HAND <-(dat.cl.child$HAND==1)*1
dat.cl.child$HAND_std_mathread <- dat.cl.child$HAND*dat.cl.child$std_mathread #create interaction variable

dat.cl.child$cl_sustainability_score.COMBO<-(dat.cl.child[,"cl_sustainability_future_score"]*18+dat.cl.child[,"cl_sustainability_inst_score"]*16+dat.cl.child[,"cl_sustainability_classes_score"]*9+dat.cl.child[,"cl_sustainability_MOE_score"]*9+dat.cl.child[,"cl_sustainability_shura_score"]*9)/(18+16+9+9)

# CL perception outcome: cl_sustainability_score.COMBO

subset106<-(is.na(eval(parse(text='(dat.cl.child$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.child$TREAT==1)'))&(!is.na(dat.cl.child[,"cl_sustainability_score.COMBO"]))&(!is.na(dat.cl.child$wt))
y.tr106<-(dat.cl.child[subset106, "cl_sustainability_score.COMBO"]-
            mean(dat.cl.child[subset106&dat.cl.child$HAND==0, "cl_sustainability_score.COMBO"], na.rm=TRUE))/sd(dat.cl.child[subset106, "cl_sustainability_score.COMBO"], na.rm=TRUE)
XX106<-as.matrix(cbind(dat.cl.child[subset106, c("TREAT", "HAND", "std_mathread", "HAND_std_mathread")], sapply(dat.cl.child[subset106, cov1.cl], dm)))
lm106<-lm( formula(paste("y.tr106", "XX106", sep="~")),  weights=dat.cl.child$wt[subset106])
res106<-coef_test(lm106, vcov=vcovCR(lm106, cluster=dat.cl.child$CLUSTER[subset106], type="CR2"))

#full regression output for supplementary appendix
res106_full<-as.data.frame(res106)

res106<-as.data.frame(res106[2:4,]) # keep second row of output 

# CL perception outcome: cl_sustainability_future_score

subset101<-(is.na(eval(parse(text='(dat.cl.child$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.child$TREAT==1)'))&(!is.na(dat.cl.child[,"cl_sustainability_future_score"]))&(!is.na(dat.cl.child$wt))
y.tr101<-(dat.cl.child[subset101, "cl_sustainability_future_score"]-
          mean(dat.cl.child[subset101&dat.cl.child$HAND==0, "cl_sustainability_future_score"], na.rm=TRUE))/sd(dat.cl.child[subset101&dat.cl.child$HAND==0, "cl_sustainability_future_score"], na.rm=TRUE)
XX101<-as.matrix(cbind(dat.cl.child[subset101, c("TREAT", "HAND", "std_mathread", "HAND_std_mathread")], sapply(dat.cl.child[subset101, cov1.cl], dm)))
lm101<-lm( formula(paste("y.tr101", "XX101", sep="~")),  weights=dat.cl.child$wt[subset101])
res101<-coef_test(lm101, vcov=vcovCR(lm101, cluster=dat.cl.child$CLUSTER[subset101], type="CR2"))

#full regression output for supplementary appendix
res101_full<-as.data.frame(res101)

res101<-as.data.frame(res101[2:4,]) # keep second row of output 

# CL perception outcome: cl_sustainability_inst_score
subset102<-(is.na(eval(parse(text='(dat.cl.child$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.child$TREAT==1)'))&(!is.na(dat.cl.child[,"cl_sustainability_inst_score"]))&(!is.na(dat.cl.child$wt))
y.tr102<-(dat.cl.child[subset102, "cl_sustainability_inst_score"]-
            mean(dat.cl.child[subset102&dat.cl.child$HAND==0, "cl_sustainability_inst_score"], na.rm=TRUE))/sd(dat.cl.child[subset102&dat.cl.child$HAND==0, "cl_sustainability_inst_score"], na.rm=TRUE)
XX102<-as.matrix(cbind(dat.cl.child[subset102, c("TREAT", "HAND", "std_mathread", "HAND_std_mathread")], sapply(dat.cl.child[subset102, cov1.cl], dm)))
lm102<-lm( formula(paste("y.tr102", "XX102", sep="~")),  weights=dat.cl.child$wt[subset102])
res102<-coef_test(lm102, vcov=vcovCR(lm102, cluster=dat.cl.child$CLUSTER[subset102], type="CR2"))

#full regression output for supplementary appendix
res102_full<-as.data.frame(res102)

res102<-as.data.frame(res102[2:4,]) # keep second row of output 

# CL perception outcome: cl_sustainability_classes_score

subset103<-(is.na(eval(parse(text='(dat.cl.child$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.child$TREAT==1)'))&(!is.na(dat.cl.child[,"cl_sustainability_classes_score"]))&(!is.na(dat.cl.child$wt))
y.tr103<-(dat.cl.child[subset103, "cl_sustainability_classes_score"]-
            mean(dat.cl.child[subset103&dat.cl.child$HAND==0, "cl_sustainability_classes_score"], na.rm=TRUE))/sd(dat.cl.child[subset103&dat.cl.child$HAND==0, "cl_sustainability_classes_score"], na.rm=TRUE)
XX103<-as.matrix(cbind(dat.cl.child[subset103, c("TREAT", "HAND", "std_mathread", "HAND_std_mathread")], sapply(dat.cl.child[subset103, cov1.cl], dm)))
lm103<-lm( formula(paste("y.tr103", "XX103", sep="~")),  weights=dat.cl.child$wt[subset103])
res103<-coef_test(lm103, vcov=vcovCR(lm103, cluster=dat.cl.child$CLUSTER[subset103], type="CR2"))

#full regression output for supplementary appendix
res103_full<-as.data.frame(res103)

res103<-as.data.frame(res103[2:4,]) # keep second row of output 

# CL perception outcome: cl_sustainability_MOE_score

subset104<-(is.na(eval(parse(text='(dat.cl.child$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.child$TREAT==1)'))&(!is.na(dat.cl.child[,"cl_sustainability_MOE_score"]))&(!is.na(dat.cl.child$wt))
y.tr104<-(dat.cl.child[subset104, "cl_sustainability_MOE_score"]-
            mean(dat.cl.child[subset104&dat.cl.child$HAND==0, "cl_sustainability_MOE_score"], na.rm=TRUE))/sd(dat.cl.child[subset104&dat.cl.child$HAND==0, "cl_sustainability_MOE_score"], na.rm=TRUE)
XX104<-as.matrix(cbind(dat.cl.child[subset104, c("TREAT", "HAND", "std_mathread", "HAND_std_mathread")], sapply(dat.cl.child[subset104, cov1.cl], dm)))
lm104<-lm( formula(paste("y.tr104", "XX104", sep="~")),  weights=dat.cl.child$wt[subset104])
res104<-coef_test(lm104, vcov=vcovCR(lm104, cluster=dat.cl.child$CLUSTER[subset104], type="CR2"))

#full regression output for supplementary appendix
res104_full<-as.data.frame(res104)

res104<-as.data.frame(res104[2:4,]) # keep second row of output 

# CL perception outcome: cl_sustainability_shura_score

subset105<-(is.na(eval(parse(text='(dat.cl.child$TREAT==1)')))==FALSE)&
  eval(parse(text='(dat.cl.child$TREAT==1)'))&(!is.na(dat.cl.child[,"cl_sustainability_shura_score"]))&(!is.na(dat.cl.child$wt))
y.tr105<-(dat.cl.child[subset105, "cl_sustainability_shura_score"]-
            mean(dat.cl.child[subset105&dat.cl.child$HAND==0, "cl_sustainability_shura_score"], na.rm=TRUE))/sd(dat.cl.child[subset105&dat.cl.child$HAND==0, "cl_sustainability_shura_score"], na.rm=TRUE)
XX105<-as.matrix(cbind(dat.cl.child[subset105, c("TREAT", "HAND", "std_mathread", "HAND_std_mathread")], sapply(dat.cl.child[subset105, cov1.cl], dm)))
lm105<-lm( formula(paste("y.tr105", "XX105", sep="~")),  weights=dat.cl.child$wt[subset105])
res105<-coef_test(lm105, vcov=vcovCR(lm105, cluster=dat.cl.child$CLUSTER[subset105], type="CR2"))

#full regression output for supplementary appendix
res105_full<-as.data.frame(res105)

res105<-as.data.frame(res105[2:4,]) # keep second row of output 

cl_test_score <- t(
  cbind(
    cbind(paste(c(round(res106$beta, 2),length(lm106$residuals))),c(sapply(res106$SE, addParens, 2),"")),
    cbind(paste(c(round(res101$beta, 2),length(lm101$residuals))),c(sapply(res101$SE, addParens, 2),"")),
    cbind(paste(c(round(res102$beta, 2),length(lm102$residuals))),c(sapply(res102$SE, addParens, 2),"")),
    cbind(paste(c(round(res103$beta, 2),length(lm103$residuals))),c(sapply(res103$SE, addParens, 2),"")),
    cbind(paste(c(round(res104$beta, 2),length(lm104$residuals))),c(sapply(res104$SE, addParens, 2),"")),
    cbind(paste(c(round(res105$beta, 2),length(lm105$residuals))),c(sapply(res105$SE, addParens, 2),""))
  )
)

cl_test_score_print <- data.frame(
  Outcome = c("Combined sustainability index","",
              "Community provision for future classes","",
              "Confidence in community institutions","",
              "Confidence that school will be sustained","",
              "MOE provisions for funding teachers","",
              "Shura provisions for future classes",""),
  Treatment = cl_test_score[,1],
  Community.Mean.Test.Score = cl_test_score[,2],
  Treatment.X.Mean.Test.Score = cl_test_score[,3],
  N=cl_test_score[,4])


sink(file="tabs-figs/cl_sustainability_endline_child_scores_interaction.tex")
print(xtable(cl_test_score_print,
             caption="\\label{tab:endline_sustainability_scores_int} Correlations of Community Leaders' Perceptions of the Success of the Intervention (Endline Sustainability Outcomes) with Children's Actual Performance in Tests"),
      include.rownames=F,
      caption.placement = "top")
sink()

######################################################
######################################################
######################################################
## Supplementary Appendix With Full Regression Results
######################################################
######################################################
######################################################

######################################################
#### FULL COVARIATE OUTPUT FOR FIGURE IN MAIN PAPER 
######################################################

# combine all the main hh and child results into a table with full covariates

res1full_tab <- data.frame(Coef. = round(res1full$beta, 2),
                           SE = sapply(round(res1full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res1full_tab) <- c("intercept",
                            "Treatment", "hhhead_child", "girl", "age", "int_lang_pashto", "hh_eth_hazara",
                            "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer","hhhead_age", "hhhead_schoolyears",
                            "hh_num", "hh_jeribs", "hh_animal_sheep","childrenschool_km", "hhhead_job_laborer",
                            "hhhead_job_military", "hhhead_write","hhhead_read","hhhead_edu_mosque","hhhead_edu_madrassa",
                            "hhhead_edu_community","hhhead_edu_government","hhhead_edu_university","hhhead_female",
                            "hh_totalincome_2001less","hh_totalincome_2001to5000","hh_totalincome_5001to10000","hh_totalincome_10001to15000",
                            "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles",
                            "hh_own_cars","hh_own_radios","factor_wealth","hh_landown", "hh_children","PROVINCE1", "PROVINCE2",
                            "PROVINCE3", "PROVINCE4","PROVINCE5")

res2full_tab <- data.frame(Coef. = round(res2full$beta, 2),
                           SE = sapply(round(res2full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res2full_tab) <- c("intercept",
                            "Treatment", "hhhead_child", "girl", "age", "int_lang_pashto", "hh_eth_hazara",
                            "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer","hhhead_age", "hhhead_schoolyears",
                            "hh_num", "hh_jeribs", "hh_animal_sheep","childrenschool_km", "hhhead_job_laborer",
                            "hhhead_job_military", "hhhead_write","hhhead_read","hhhead_edu_mosque","hhhead_edu_madrassa",
                            "hhhead_edu_community","hhhead_edu_government","hhhead_edu_university","hhhead_female",
                            "hh_totalincome_2001less","hh_totalincome_2001to5000","hh_totalincome_5001to10000","hh_totalincome_10001to15000",
                            "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles",
                            "hh_own_cars","hh_own_radios","factor_wealth","hh_landown", "hh_children","PROVINCE1", "PROVINCE2",
                            "PROVINCE3", "PROVINCE4","PROVINCE5")

res3full_tab <- data.frame(Coef. = round(res3full$beta, 2),
                           SE = sapply(round(res3full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res3full_tab) <- c("intercept",
                            "Treatment", "int_lang_pashto", "hh_eth_hazara",
                            "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer","hhhead_age", "hhhead_schoolyears",
                            "hh_num", "hh_jeribs", "hh_animal_sheep","hhschool_km", "hhhead_job_laborer",
                            "hhhead_job_military", "hhhead_write","hhhead_read","hhhead_edu_mosque","hhhead_edu_madrassa",
                            "hhhead_edu_community","hhhead_edu_government","hhhead_edu_university","hhhead_female",
                            "hh_totalincome_2001less","hh_totalincome_2001to5000","hh_totalincome_5001to10000","hh_totalincome_10001to15000",
                            "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles",
                            "hh_own_cars","hh_own_radios","factor_wealth","hh_landown", "hh_children","PROVINCE1", "PROVINCE2",
                            "PROVINCE3", "PROVINCE4","PROVINCE5")

multimerge <- function (mylist) {
  ## mimics a recursive merge or full outer join
  unames <- unique(unlist(lapply(mylist, rownames)))
  n <- length(unames)
  out <- lapply(mylist, function(df) {
    tmp <- matrix(nr = n, nc = ncol(df), dimnames = list(unames,colnames(df)))
    tmp[rownames(df), ] <- as.matrix(df)
    rm(df); gc()
    return(tmp)
  })
  
  stopifnot( all( sapply(out, function(x) identical(rownames(x), unames)) ) )
  bigout <- do.call(cbind, out)
  colnames(bigout) <- paste(rep(names(mylist), sapply(mylist, ncol)), unlist(sapply(mylist, colnames)), sep = "_")
  return(bigout)
}

primary_equiv_results_full<-multimerge( list (one=res1full_tab, two=res2full_tab, three=res3full_tab ))

primary_equiv_results_full_tab_format_print<-xtable(primary_equiv_results_full,
                                                    caption="\\label{tab:fig2_full_regression}Primary Equivalence Results")

columns<-c("Attendance", "Std Math and Reading Score", "Household Satisfaction")
#length(lm1$residuals) =4980
#length(lm2$residuals) =3822
#length(lm3$residuals) =3750

N<-c("4980", "3822", "3750")

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', unique(N), '}', collapse=''), '\\\\')

sink(file="tabs-figs/primary_equiv_results_full_cov.tex")
print(primary_equiv_results_full_tab_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting

######################################################
#### FULL COVARIATE OUTPUT FOR FIGURE 3 IN MAIN PAPER 
######################################################

## make one table for the CL - classroom supplies
res7full_tab <- data.frame(Coef. = round(res7full$beta, 2),
                           SE = sapply(round(res7full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res7full_tab) <- c("Intercept",
                            "Treatment", "cl_int_lang_pashto", "cl_hhhead_job_farmer", "cl_hhhead_age",
                            "cl_hhead_schoolyears", "cl_school_km")

res7full_tab_format_print<-xtable(res7full_tab,
                                  caption="\\label{tab:fig3_reg_cl_classroom}Test of Potential Agency Issues: CL - Classroom Supplies")

columns<-c("CL: classroom supplies")
N<-c(length(lm7$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', unique(N), '}', collapse=''), '\\\\')
sink(file="tabs-figs/main_results_cl_classroom_supplies_full_cov.tex")
print(res7full_tab_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting

## make one table combining the full results for TS: combined fund application index, classroom supplies, and teacher paid regularly 

# TS: combined fund application index 
res8full_tab <- data.frame(Coef. = round(res8full$beta, 2),
                           SE = sapply(round(res8full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res8full_tab) <- c("Intercept",
                            "Treatment", "cv_ts")

# TS: classroom supplies 
res9full_tab <- data.frame(Coef. = round(res9full$beta, 2),
                           SE = sapply(round(res9full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res9full_tab) <- c("Intercept",
                            "Treatment", "cv_ts")

# TS: teacher paid regularly 
res11full_tab <- data.frame(Coef. = round(res11full$beta, 2),
                           SE = sapply(round(res11full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res11full_tab) <- c("Intercept",
                            "Treatment", "cv_ts")

ts_agency_results_full_1<-multimerge( list (one=res8full_tab, two=res9full_tab, three=res11full_tab ))

ts_agency_results_full_1_tab_format_print<-xtable(ts_agency_results_full_1,
                                                    caption="\\label{tab:fig3_full_cov_ts1}Test of Potential Agency Issues: Results on Teacher Funds and Supplies")

columns<-c("TS: Combined Fund Application Index", "TS: Classroom Supplies", "TS: Teacher Paid Regularly")
N<-c(length(lm8$residuals), length(lm9$residuals), length(lm11$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/fig3_full_cov_ts1.tex")
print(ts_agency_results_full_1_tab_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting

## make one table combining the full results for HH: confidence in local institutions, teacher attendance, and perception of teacher quality

# HH: confidence in local institutions
res6full_tab <- data.frame(Coef. = round(res6full$beta, 2),
                            SE = sapply(round(res6full$SE, 2),
                                              function(x) {paste0("(",x,")")}))
rownames(res6full_tab) <- c("Intercept",
                            "Treatment", "int_lang_pashto", "hh_eth_hazara",
                            "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer","hhhead_age", "hhhead_schoolyears",
                            "hh_num", "hh_jeribs", "hh_animal_sheep","hhschool_km", "hhhead_job_laborer",
                            "hhhead_job_military", "hhhead_write","hhhead_read","hhhead_edu_mosque","hhhead_edu_madrassa",
                            "hhhead_edu_community","hhhead_edu_government","hhhead_edu_university","hhhead_female",
                            "hh_totalincome_2001less","hh_totalincome_2001to5000","hh_totalincome_5001to10000","hh_totalincome_10001to15000",
                            "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles",
                            "hh_own_cars","hh_own_radios","factor_wealth","hh_landown", "hh_children","PROVINCE1", "PROVINCE2",
                            "PROVINCE3", "PROVINCE4","PROVINCE5") 

# HH: teacher attendance 
res4full_tab <- data.frame(Coef. = round(res4full$beta, 2),
                           SE = sapply(round(res4full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res4full_tab) <- c("Intercept",
                            "Treatment", "int_lang_pashto", "hh_eth_hazara",
                            "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer","hhhead_age", "hhhead_schoolyears",
                            "hh_num", "hh_jeribs", "hh_animal_sheep","hhschool_km", "hhhead_job_laborer",
                            "hhhead_job_military", "hhhead_write","hhhead_read","hhhead_edu_mosque","hhhead_edu_madrassa",
                            "hhhead_edu_community","hhhead_edu_government","hhhead_edu_university","hhhead_female",
                            "hh_totalincome_2001less","hh_totalincome_2001to5000","hh_totalincome_5001to10000","hh_totalincome_10001to15000",
                            "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles",
                            "hh_own_cars","hh_own_radios","factor_wealth","hh_landown", "hh_children","PROVINCE1", "PROVINCE2",
                            "PROVINCE3", "PROVINCE4","PROVINCE5") 

# HH: perception of teacher quality 
res5full_tab <- data.frame(Coef. = round(res5full$beta, 2),
                           SE = sapply(round(res5full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res5full_tab) <- c("Intercept",
                            "Treatment", "int_lang_pashto", "hh_eth_hazara",
                            "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer","hhhead_age", "hhhead_schoolyears",
                            "hh_num", "hh_jeribs", "hh_animal_sheep","hhschool_km", "hhhead_job_laborer",
                            "hhhead_job_military", "hhhead_write","hhhead_read","hhhead_edu_mosque","hhhead_edu_madrassa",
                            "hhhead_edu_community","hhhead_edu_government","hhhead_edu_university","hhhead_female",
                            "hh_totalincome_2001less","hh_totalincome_2001to5000","hh_totalincome_5001to10000","hh_totalincome_10001to15000",
                            "hh_totalincome_15001plus", "hh_own_tvs", "hh_own_mobiles",
                            "hh_own_cars","hh_own_radios","factor_wealth","hh_landown", "hh_children","PROVINCE1", "PROVINCE2",
                            "PROVINCE3", "PROVINCE4","PROVINCE5") 

hh_agency_results_full<-multimerge( list (one=res6full_tab, two=res4full_tab, three=res5full_tab ))

hh_agency_results_full_tab_format_print<-xtable(hh_agency_results_full,
                                                  caption="\\label{tab:fig3_full_cov_hh}Test of Potential Agency Issues: Results on HH Confidence and Perceptions of Teacher Quality and Attendance")

columns<-c("HH: Confidence in Local Institutions", "HH: Teacher Attendance", "HH: Perception of Teacher Quality")
N<-c(length(lm6$residuals), length(lm4$residuals), length(lm5$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/fig3_full_cov_hh.tex")
print(hh_agency_results_full_tab_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting

## make one table combining the full results for TS: combined motivation index, intrinsic motivation, and material motivation

# TS: combined motivation index 
res10full_tab <- data.frame(Coef. = round(res10full$beta, 2),
                           SE = sapply(round(res10full$SE, 2),
                                             function(x) {paste0("(",x,")")}))
rownames(res10full_tab) <- c("Intercept",
                             "Treatment", "cv_ts") 

# TS: intrinsic motivation 
res12full_tab <- data.frame(Coef. = round(res12full$beta, 2),
                            SE = sapply(round(res12full$SE, 2),
                                              function(x) {paste0("(",x,")")}))
rownames(res12full_tab) <- c("Intercept",
                             "Treatment", "cv_ts") 

# TS: material motivation and satisfaction 
res13full_tab <- data.frame(Treat.Effect = round(res13full$beta, 2),
                            SE = sapply(round(res13full$SE, 2),
                                              function(x) {paste0("(",x,")")}))
rownames(res13full_tab) <- c("Intercept",
                             "Treatment", "cv_ts") 

ts_agency_results_full_2<-multimerge( list (one=res10full_tab, two=res12full_tab, three=res13full_tab ))

ts_agency_results_full_2_tab_format_print<-xtable(ts_agency_results_full_2,
                                                  caption="\\label{tab:fig3_full_cov_ts2}Test of Potential Agency Issues - Results on Teacher Motivation")


columns<-c("TS: Combined Motivation Index", "TS: Intrinsic Motivation", "TS: Material Motivation and Satisfaction")
N<-c(length(lm10$residuals), length(lm12$residuals), length(lm13$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/fig3_full_cov_ts2.tex")
print(ts_agency_results_full_2_tab_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting

######################################################
#### FULL COVARIATE OUTPUT FOR TABLE 2 IN MAIN PAPER 
######################################################

# make one table with the equivalency outcome 
# community desire to continue CBE
Table2_format_equiv <- data.frame(Coef. = round(res14full$beta, 2),
                                  SE = sapply(round(res14full$SE, 2),
                                                    function(x) {paste0("(",x,")")}))
rownames(Table2_format_equiv) <- c("Intercept","Treatment", "CL_int_lang_pashto",
                                   "CL_hhhead_job_farmer", "CL_hhead_age", "CL_clschool_km")

Table2_format_equiv_print<-xtable(Table2_format_equiv,
                                  caption="\\label{tab:follow_up_full_equiv}Community Leaders' Longer-term Perceptions of CBE Sustainability: Equivalency Outcome")

columns<-c("Community Desire to Continue CBE")
N<-c(length(lm14$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/cl_follow_up_sustainability_tomod_full_equiv.tex")
print(Table2_format_equiv_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting

# make one table with the non-equivalency outcomes 

# combined sustainability index
res15full_tab <- data.frame(Coef. = round(res15full$beta, 2),
                                      SE = sapply(round(res15full$SE, 2),
                                                        function(x) {paste0("(",x,")")}))
rownames(res15full_tab) <- c("Intercept","Treatment", "CL_int_lang_pashto",
                                       "CL_hhhead_job_farmer", "CL_hhead_age", "CL_clschool_km")

# initiative to have CBE sustained
res16full_tab <- data.frame(Coef. = round(res16full$beta, 2),
                                      SE = sapply(round(res16full$SE, 2),
                                                        function(x) {paste0("(",x,")")}))
rownames(res16full_tab) <- c("Intercept","Treatment", "CL_int_lang_pashto",
                                       "CL_hhhead_job_farmer", "CL_hhead_age", "CL_clschool_km")

# Provisions for sustainability without NGO 
res17full_tab <- data.frame(Coef. = round(res17full$beta, 2),
                                      SE = sapply(round(res17full$SE, 2),
                                                        function(x) {paste0("(",x,")")}))
rownames(res17full_tab) <- c("Intercept","Treatment ", "CL_int_lang_pashto",
                                       "CL_hhhead_job_farmer", "CL_hhead_age", "CL_clschool_km")

# Confidence that school will sustain
res18full_full <- data.frame(Coef. = round(res18full$beta, 2),
                                      SE = sapply(round(res18full$SE, 2),
                                                        function(x) {paste0("(",x,")")}))
rownames(res18full_full) <- c("Intercept","Treatment", "CL_int_lang_pashto",
                                       "CL_hhhead_job_farmer", "CL_hhead_age", "CL_clschool_km")

#  Continued CBE operations in spring 2018
res19full_tab <- data.frame(Coef. = round(res19full$beta, 2),
                                     SE = sapply(round(res19full$SE, 2),
                                                        function(x) {paste0("(",x,")")}))
rownames(res19full_tab) <- c("Intercept","Treatment", "CL_int_lang_pashto",
                                       "CL_hhhead_job_farmer", "CL_hhead_age", "CL_clschool_km")

cl_longterm_non_equiv_results_full<-multimerge( list (one=res15full_tab, two=res16full_tab, three=res17full_tab, 
                                                      four=res18full_full, five=res19full_tab))

cl_longterm_non_equiv_results_full_format_print<-xtable(cl_longterm_non_equiv_results_full,
                                                  caption="\\label{tab:tab2_cl_follow_up_sustainability_full_nonequiv}Community Leaders' Longer-Term Perceptions of CBE Sustainability - Non-Equivalency Outcomes")

columns<-c("Combined Sustainability Index", "Initiative to have CBE Sustained", "Provisions for Sustainability Without NGO",
           "Confidence that School will Sustain", "Continued CBE Operations in Spring 2018")
N<-c(length(lm15$residuals), length(lm16$residuals), length(lm17$residuals),
     length(lm18$residuals), length(lm19$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab2_cl_follow_up_sustainability_full_nonequiv.tex")
print(cl_longterm_non_equiv_results_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting

#########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A8 IN MAIN APPENDIX
#########################################################

# one table with the attendance and reading/math hte results by gender

# girls and boys' attendance hte results
res.het1.full_tab <- data.frame(Coef. = round(res.het1.full$beta, 2),
                                      SE = sapply(round(res.het1.full$SE, 2),
                                                        function(x) {paste0("(",x,")")}))

rownames(res.het1.full_tab) <- c("Girls - Intercept", "Boys - Intercept", "Girls - Treatment",
                                       "Boys - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                       "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                       "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                       "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                       "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                       "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                       "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                       "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# girls and boys' test scores hte results
res.het2.full_tab <- data.frame(Coef. = round(res.het2.full$beta, 2),
                                       SE = sapply(round(res.het2.full$SE, 2),
                                                         function(x) {paste0("(",x,")")}))

rownames(res.het2.full_tab) <- c("Girls - Intercept", "Boys - Intercept", "Girls - Treatment",
                                        "Boys - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                        "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                        "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                        "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                        "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                        "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                        "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                        "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a8_gender_hte_full<-multimerge( list (one=res.het1.full_tab, two=res.het2.full_tab))

tab_a8_gender_hte_full_format_print<-xtable(tab_a8_gender_hte_full,
                                                        caption="\\label{tab:tab_a8_gender_hte_full}Heterogeneous Treatment Effects for Attendance and Test Scores by Gender")

columns<-c("Attendance", "Math and Reading Scores")
N<-c(length(lm.het1$residuals), length(lm.het2$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a8_gender_hte_full.tex")
print(tab_a8_gender_hte_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting and I added in another column with the het. test p-value  

# one table with the attendance and reading/math hte results by ethnic majority and minority status

# ethnic majority and minority attendance hte results
res.het3.full_tab <- data.frame(Coef. = round(res.het3.full$beta, 2),
                                      SE = sapply(round(res.het3.full$SE, 2),
                                                        function(x) {paste0("(",x,")")}))

rownames(res.het3.full_tab) <- c("Ethnic Majority - Intercept", "Ethnic Minority - Intercept", "Ethnic Majority - Treatment",
                                       "Ethnic Minority - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                       "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                       "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                       "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                       "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                       "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                       "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                       "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# ethnic majority and minority math/reading test hte results
res.het4.full_tab <- data.frame(Coef. = round(res.het4.full$beta, 2),
                                              SE = sapply(round(res.het4.full$SE, 2),
                                                                function(x) {paste0("(",x,")")}))

rownames(res.het4.full_tab) <- c("Ethnic Majority - Intercept", "Ethnic Minority - Intercept", "Ethnic Majority - Treatment",
                                               "Ethnic Minority - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                               "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                               "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                               "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                               "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                               "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                               "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                               "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a8_ethmajmin_hte_full<-multimerge( list (one=res.het3.full_tab, two=res.het4.full_tab))

tab_a8_ethmajmin_hte_full_format_print<-xtable(tab_a8_ethmajmin_hte_full,
                                            caption="\\label{tab:tab_a8_ethmajmin_hte_fulll}Heterogeneous Treatment Effects for Attendance and Test Scores by Ethnic Majority/Minority Status")

columns<-c("Attendance", "Math and Reading Scores")
N<-c(length(lm.het3$residuals), length(lm.het4$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a8_ethmajmin_hte_fulll.tex")
print(tab_a8_ethmajmin_hte_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting and I added in another column with the het. test p-value  

# one table with the attendance and reading/math hte results by cl same/diff ethnicity 

# cl same / diff ethnicity attendance hte results
res.het5.full_tab <- data.frame(Coef. = round(res.het5.full$beta, 2),
                                             SE = sapply(round(res.het5.full$SE, 2),
                                                               function(x) {paste0("(",x,")")}))

rownames(res.het5.full_tab) <- c("CL Same Ethnicity - Intercept", "CL Diff Ethnicity - Intercept", "CL Same Ethnicity - Treatment",
                                              "CL Diff Ethnicity - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                              "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# cl same / diff ethnicity test scores hte results
res.het6.full_tab<- data.frame(Coef. = round(res.het6.full$beta, 2),
                                         SE = sapply(round(res.het6.full$SE, 2),
                                                            function(x) {paste0("(",x,")")}))

rownames(res.het6.full_tab) <- c("CL Same Ethnicity - Intercept", "CL Diff Ethnicity - Intercept", "CL Same Ethnicity - Treatment",
                                           "CL Diff Ethnicity - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                           "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                           "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                           "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                           "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                           "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                           "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                           "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a8_cleth_hte_full<-multimerge( list (one=res.het5.full_tab, two=res.het6.full_tab))

tab_a8_cleth_hte_full_format_print<-xtable(tab_a8_cleth_hte_full,
                                               caption="\\label{tab:tab_a8_cleth_hte_full}Heterogeneous Treatment Effects for Attendance and Test Scores by Community Leader Ethnic Status")

columns<-c("Attendance", "Math and Reading Scores")
N<-c(length(lm.het4$residuals), length(lm.het5$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a8_cleth_hte_full.tex")
print(tab_a8_cleth_hte_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting and I added in another column with the het. test p-value  

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A9 IN MAIN APPENDIX
##########################################################

# one table with the attendance and reading/math hte results by cl having school-aged children versus not

# cl has school aged children vs. not attendance hte results
res.het7.full_tab<- data.frame(Coef. = round(res.het7.full$beta, 2),
                                        SE = sapply(round(res.het7.full$SE, 2),
                                                          function(x) {paste0("(",x,")")}))

rownames(res.het7.full_tab) <- c("Has Children - Intercept", "No Children - Intercept", "Has Children - Treatment",
                                          "No Children - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                          "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                          "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                          "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                          "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                          "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                          "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                          "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# cl has school aged children vs. not test score hte results
res.het8.full_tab<- data.frame(Coef. = round(res.het8.full$beta, 2),
                                   SE = sapply(round(res.het8.full$SE, 2),
                                                     function(x) {paste0("(",x,")")}))

rownames(res.het8.full_tab) <- c("Has Children - Intercept", "No Children - Intercept", "Has Children - Treatment",
                                     "No Children - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                     "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                     "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                     "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                     "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                     "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                     "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                     "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a9_clchild_hte_full1<-multimerge( list (one=res.het7.full_tab, two=res.het8.full_tab))

tab_a9_clchild_hte_full1_format_print<-xtable(tab_a9_clchild_hte_full1,
                                           caption="\\label{tab:tab_a9_clchild_hte_full1}Heterogeneous Treatment Effects for Attendance and Test Scores by Community Leader Having School-Aged Children")

columns<-c("Attendance", "Math and Reading Scores")
N<-c(length(lm.het7$residuals), length(lm.het8$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a9_clchild_hte_full1.tex")
print(tab_a9_clchild_hte_full1_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting and I added in another column with the het. test p-value  

# one table with the household satisfaction, confidence, perceived teacher attendance, and quality results by cl having school-aged children versus not

# cl has school aged children vs. not HH satisfaction with access hte results

res.het9.full_tab<- data.frame(Coef. = round(res.het9.full$beta, 2),
                                  SE = sapply(round(res.het9.full$SE, 2),
                                                    function(x) {paste0("(",x,")")}))

rownames(res.het9.full_tab) <- c("Has Children - Intercept", "No Children - Intercept", "Has Children - Treatment",
                                    "No Children - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                    "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                    "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                    "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                    "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                    "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                    "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                    "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# cl has school aged children vs. not HH confidence in local instns. hte results

res.het10.full_tab<- data.frame(Coef. = round(res.het10.full$beta, 2),
                               SE = sapply(round(res.het10.full$SE, 2),
                                           function(x) {paste0("(",x,")")}))

rownames(res.het10.full_tab) <- c("Has Children - Intercept", "No Children - Intercept", "Has Children - Treatment",
                                 "No Children - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                 "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                 "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                 "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                 "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                 "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                 "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                 "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# cl has school aged children vs. not HH perceived teacher attendance hte results

res.het11.full_tab<- data.frame(Coef. = round(res.het11.full$beta, 2),
                                SE = sapply(round(res.het11.full$SE, 2),
                                            function(x) {paste0("(",x,")")}))

rownames(res.het11.full_tab) <- c("Has Children - Intercept", "No Children - Intercept", "Has Children - Treatment",
                                  "No Children - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                  "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                  "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                  "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                  "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                  "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                  "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                  "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# cl has school aged children vs. not HH perceived teacher quality hte results

res.het12.full_tab<- data.frame(Coef. = round(res.het12.full$beta, 2),
                                SE = sapply(round(res.het12.full$SE, 2),
                                            function(x) {paste0("(",x,")")}))

rownames(res.het12.full_tab) <- c("Has Children - Intercept", "No Children - Intercept", "Has Children - Treatment",
                                  "No Children - Treatment", "int_lang_pashto", "hhhead_job_farmer", "hhhead_age",
                                  "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                  "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                  "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                  "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                  "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                  "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                  "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a9_clchild__hh_hte_full2<-multimerge( list (one=res.het9.full_tab, two=res.het10.full_tab, three=res.het11.full_tab, four=res.het12.full_tab))

tab_a9_clchild__hh_hte_full2_print<-xtable(tab_a9_clchild__hh_hte_full2,
                            caption="\\label{tab:hte-cl-haschild-hh-full}Heterogeneous Treatment Effects for Household Outcomes by Community Leader Having School-Aged Children")

columns<-c("HH Satisfaction With Access", "HH Confidence in Local Instns.", "HH Perceived Teacher Attendance",
           "HH Perceived Teacher Quality")
N<-c(length(lm.het9$residuals), length(lm.het10$residuals), length(lm.het11$residuals),
     length(lm.het12$residuals))

addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab-a9-hte-cl-haschild-hh-full.tex")
print(tab_a9_clchild__hh_hte_full2_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting and I added in another column with the het. test p-value  

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A10 IN MAIN APPENDIX
##########################################################

# one table for the child outcomes and covariates
# attendance
res65_full_tab<- data.frame(Coef. = round(res65_full$beta, 2),
                               SE = sapply(round(res65_full$SE, 2),
                                           function(x) {paste0("(",x,")")}))

rownames(res65_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                                 "HAND_kapisa", "HAND_parwan", "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", 
                                 "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                                 "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                                 "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                                 "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                                 "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                                 "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                                 "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                                 "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# test scores
res66_full_tab<- data.frame(Coef. = round(res66_full$beta, 2),
                            SE = sapply(round(res66_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res66_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a10_child_ca_sum_full<-multimerge( list (one=res65_full_tab, two=res66_full_tab))

tab_a10_child_ca_sum_full_format_print<-xtable(tab_a10_child_ca_sum_full,
                                              caption="\\label{tab:tab_a10_child_ca_sum_full}Interaction Effects Regressions with Village-Level General Management Capacity Assessment [CA] Sum Scores with Main Child Outcomes")

columns<-c("Attendance", "Child Test Score")
N<-c(length(lm65$residuals), length(lm66$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a10_child_ca_sum_full.tex")
print(tab_a10_child_ca_sum_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting 


# one table for the household agency outcomes and covariates

# hh confidence in local institutions
res67_full_tab<- data.frame(Coef. = round(res67_full$beta, 2),
                            SE = sapply(round(res67_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res67_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# hh perceived teacher quality
res68_full_tab<- data.frame(Coef. = round(res68_full$beta, 2),
                            SE = sapply(round(res68_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res68_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# hh perceived teacher attendance
res69_full_tab<- data.frame(Coef. = round(res69_full$beta, 2),
                            SE = sapply(round(res69_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res69_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a10_hh_ca_sum_full<-multimerge( list (one=res67_full_tab, two=res68_full_tab, three=res69_full_tab))

tab_a10_hh_ca_sum_full_format_print<-xtable(tab_a10_hh_ca_sum_full,
                                               caption="\\label{tab:tab_a10_hh_ca_sum_full}Interaction Effects Regressions with Village-Level General Management Capacity Assessment [CA] Sum Scores with Agency Outcomes for Households")

columns<-c("HH Conf. in Local Instns.", "HH Perceived Teacher Quality", "HH Perceived Teacher Attendance")
N<-c(length(lm67$residuals), length(lm68$residuals), length(lm68$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a10_hh_ca_sum_full.tex")
print(tab_a10_hh_ca_sum_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little manual formatting  

# one table for the community leader agency outcome and covariates

res70_full_tab<- data.frame(Coef. = round(res70_full$beta, 2),
                            SE = sapply(round(res70_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res70_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "school_km")

tab_a10_cl_ca_sum_full_format_print<-xtable(res70_full_tab,
                                            caption="\\label{tab:tab_a10_cl_ca_sum_full}Interaction Effects Regressions with Village-Level General Management Capacity Assessment [CA] Sum Scores with Agency Outcomes for Community Leaders")

columns<-c("CL Classroom Funds Score")
N<-c(length(lm70$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a10_cl_ca_sum_full.tex")
print(tab_a10_cl_ca_sum_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

# one table for the teacher agency outcomes and covariates

# teacher fund application index
res71_full_tab<- data.frame(Coef. = round(res71_full$beta, 2),
                            SE = sapply(round(res71_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res71_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")


#teacher classroom supplies scores
res72_full_tab<- data.frame(Coef. = round(res72_full$beta, 2),
                            SE = sapply(round(res72_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res72_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

#teacher motivation index
res73_full_tab<- data.frame(Coef. = round(res73_full$beta, 2),
                            SE = sapply(round(res73_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res73_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

#teacher paid regularly
res74_full_tab<- data.frame(Coef. = round(res74_full$beta, 2),
                            SE = sapply(round(res74_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res74_full_tab) <- c("Intercept", "Treatment", "CA sum score", "Treatment X CA sum score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

tab_a10_ts_ca_sum_full<-multimerge( list (one=res71_full_tab, two=res72_full_tab, three=res73_full_tab, four=res74_full_tab))

tab_a10_ts_ca_sum_full_format_print<-xtable(tab_a10_ts_ca_sum_full,
                                            caption="\\label{tab:tab_a10_ts_ca_sum_full}Interaction Effects Regressions with Village-Level General Management Capacity Assessment [CA] Sum Scores with Agency Outcomes for Teachers")

columns<-c("TS Fund Application Index", "TS Classroom Supplies Score", "TS Motivation Index", "TS Paid Regularly")
N<-c(length(lm71$residuals), length(lm72$residuals), length(lm73$residuals), length(lm74$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a10_ts_ca_sum_full.tex")
print(tab_a10_ts_ca_sum_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A11 IN MAIN APPENDIX
##########################################################

# one table for the child outcomes and covariates
# attendance
res77_full_tab<- data.frame(Coef. = round(res77_full$beta, 2),
                            SE = sapply(round(res77_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res77_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# test scores
res78_full_tab<- data.frame(Coef. = round(res78_full$beta, 2),
                            SE = sapply(round(res78_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res78_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a11_child_ca_pca_full<-multimerge( list (one=res77_full_tab, two=res78_full_tab))

tab_a11_child_ca_pca_full_format_print<-xtable(tab_a11_child_ca_pca_full,
                                               caption="\\label{tab:tab_a11_child_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Previous Capacity Building of CDCs with Main Child Outcomes")

columns<-c("Attendance", "Child Test Score")
N<-c(length(lm77$residuals), length(lm78$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a11_child_ca_pca_full.tex")
print(tab_a11_child_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

# one table for the household agency outcomes and covariates

# hh confidence in local institutions
res79_full_tab<- data.frame(Coef. = round(res79_full$beta, 2),
                            SE = sapply(round(res79_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res79_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# hh perceived teacher quality
res80_full_tab<- data.frame(Coef. = round(res80_full$beta, 2),
                            SE = sapply(round(res80_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res80_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# hh perceived teacher attendance
res81_full_tab<- data.frame(Coef. = round(res81_full$beta, 2),
                            SE = sapply(round(res81_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res81_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a11_hh_ca_pca_full<-multimerge( list (one=res79_full_tab, two=res80_full_tab, three=res81_full_tab))

tab_a11_hh_ca_pca_full_format_print<-xtable(tab_a11_hh_ca_pca_full,
                                            caption="\\label{tab:tab_a11_hh_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Previous Capacity Building of CDCs with Agency Outcomes for Households")


columns<-c("HH Conf. in Local Instns.", "HH Perceived Teacher Quality", "HH Perceived Teacher Attendance")
N<-c(length(lm79$residuals), length(lm80$residuals), length(lm81$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a11_hh_ca_pca_full.tex")
print(tab_a11_hh_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

# one table for the community leader agency outcome and covariates

res82_full_tab<- data.frame(Coef. = round(res82_full$beta, 2),
                            SE = sapply(round(res82_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res82_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "school_km")

tab_a11_cl_ca_pca_full_format_print<-xtable(res82_full_tab,
                                            caption="\\label{tab:tab_a11_cl_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Previous Capacity Building of CDCs with Agency Outcomes for Community Leaders")

columns<-c("CL Classroom Funds Score")
N<-c(length(lm82$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a11_cl_ca_pca_full.tex")
print(tab_a11_cl_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

# one table for the teacher agency outcomes and covariates

# teacher fund application index
res83_full_tab<- data.frame(Coef. = round(res83_full$beta, 2),
                            SE = sapply(round(res83_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res83_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")


#teacher classroom supplies scores
res84_full_tab<- data.frame(Coef. = round(res84_full$beta, 2),
                            SE = sapply(round(res84_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res84_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

#teacher motivation index
res85_full_tab<- data.frame(Coef. = round(res85_full$beta, 2),
                            SE = sapply(round(res85_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res85_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

#teacher paid regularly
res86_full_tab<- data.frame(Coef. = round(res86_full$beta, 2),
                            SE = sapply(round(res86_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res86_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

tab_a11_ts_ca_pca_full<-multimerge( list (one=res83_full_tab, two=res84_full_tab, three=res85_full_tab, four=res86_full_tab))

tab_a11_ts_ca_pca_full_format_print<-xtable(tab_a11_ts_ca_pca_full,
                                            caption="\\label{tab:tab_a11_ts_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Previous Capacity Building of CDCs with Agency Outcomes for Teachers")

columns<-c("TS Fund Application Index", "TS Classroom Supplies Score", "TS Motivation Index", "TS Paid Regularly")
N<-c(length(lm83$residuals), length(lm84$residuals), length(lm85$residuals), length(lm86$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')
sink(file="tabs-figs/tab_a11_ts_ca_pca_full.tex")
print(tab_a11_ts_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A12 IN MAIN APPENDIX
##########################################################

# one table for the child outcomes and covariates
# attendance
res89_full_tab<- data.frame(Coef. = round(res89_full$beta, 2),
                            SE = sapply(round(res89_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res89_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# test scores
res90_full_tab<- data.frame(Coef. = round(res90_full$beta, 2),
                            SE = sapply(round(res90_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res90_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a12_child_ca_pca_full<-multimerge( list (one=res89_full_tab, two=res90_full_tab))

tab_a12_child_ca_pca_full_format_print<-xtable(tab_a12_child_ca_pca_full,
                                               caption="\\label{tab:tab_a12_child_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Current CDC Functionality with Main Child Outcomes")


columns<-c("Attendance", "Child Test Score")
N<-c(length(lm89$residuals), length(lm90$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a12_child_ca_pca_full.tex")
print(tab_a12_child_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

# one table for the household agency outcomes and covariates

# hh confidence in local institutions
res91_full_tab<- data.frame(Coef. = round(res91_full$beta, 2),
                            SE = sapply(round(res91_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res91_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# hh perceived teacher quality
res92_full_tab<- data.frame(Coef. = round(res92_full$beta, 2),
                            SE = sapply(round(res92_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res92_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

# hh perceived teacher attendance
res93_full_tab<- data.frame(Coef. = round(res93_full$beta, 2),
                            SE = sapply(round(res93_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res93_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears",
                              "hh_num", "hh_jeribs",  "hh_animal_sheep", "school_km", 
                              "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", 
                              "hhhead_edu_mosque", "hhhead_edu_madrassa", "hhhead_edu_community", "hhhead_edu_government", 
                              "hhhead_edu_university", "hhhead_female", "hh_totalincome_2000less", "hh_totalincome_2001to5000",
                              "hh_totalincome_5001to10000", "hh_totalincome_10001to15000", "hh_totalincome_15001plus", "hh_own_tvs",
                              "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children",
                              "PROVINCE1", "PROVINCE2", "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a12_hh_ca_pca_full<-multimerge( list (one=res91_full_tab, two=res92_full_tab, three=res93_full_tab))

tab_a12_hh_ca_pca_full_format_print<-xtable(tab_a12_hh_ca_pca_full,
                                            caption="\\label{tab:tab_a12_hh_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Current CDC Functionality with Agency Outcomes for Households")

columns<-c("HH Conf. in Local Instns.", "HH Perceived Teacher Quality", "HH Perceived Teacher Attendance")
N<-c(length(lm91$residuals), length(lm92$residuals), length(lm93$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a12_hh_ca_pca_full.tex")
print(tab_a12_hh_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

# one table for the community leader agency outcome and covariates

res94_full_tab<- data.frame(Coef. = round(res94_full$beta, 2),
                            SE = sapply(round(res94_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res94_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "int_lang_pashto", 
                              "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "school_km")

tab_a12_cl_ca_pca_full_format_print<-xtable(res94_full_tab,
                                            caption="\\label{tab:tab_a12_cl_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Current CDC Functionality with Agency Outcomes for Community Leaders")

columns<-c("CL Classroom Funds Score")
N<-c(length(lm94$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a12_cl_ca_pca_full.tex")
print(tab_a12_cl_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

# one table for the teacher agency outcomes and covariates

# teacher fund application index
res95_full_tab<- data.frame(Coef. = round(res95_full$beta, 2),
                            SE = sapply(round(res95_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res95_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")


#teacher classroom supplies scores
res96_full_tab<- data.frame(Coef. = round(res96_full$beta, 2),
                            SE = sapply(round(res96_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res96_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

#teacher motivation index
res97_full_tab<- data.frame(Coef. = round(res97_full$beta, 2),
                            SE = sapply(round(res97_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res97_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

#teacher paid regularly
res98_full_tab<- data.frame(Coef. = round(res98_full$beta, 2),
                            SE = sapply(round(res98_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res98_full_tab) <- c("Intercept", "Treatment", "CA PCA score", "Treatment X CA PCA score",
                              "HAND_kapisa", "HAND_parwan", "cv_ts")

tab_a12_ts_ca_pca_full<-multimerge( list (one=res95_full_tab, two=res96_full_tab, three=res97_full_tab, four=res98_full_tab))

tab_a12_ts_ca_pca_full_format_print<-xtable(tab_a12_ts_ca_pca_full,
                                            caption="\\label{tab:tab_a12_ts_ca_pca_full}Interaction Effects Regressions with Village-Level PCA Scores of Current CDC Functionality with Agency Outcomes for Teachers")

columns<-c("TS Fund Application Index", "TS Classroom Supplies Score", "TS Motivation Index", "TS Paid Regularly")
N<-c(length(lm95$residuals), length(lm96$residuals), length(lm97$residuals), length(lm98$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a12_ts_ca_pca_full.tex")
print(tab_a12_ts_ca_pca_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A13 IN MAIN APPENDIX
##########################################################

# one table for the community leader outcomes
#combined sustainability index
res30_full_tab<- data.frame(Coef. = round(res30_full$beta, 2),
                            SE = sapply(round(res30_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res30_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer",
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#community provision for future classes
res31_full_tab<- data.frame(Treat.Effect  = round(res31_full$beta, 2),
                            SE = sapply(round(res31_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res31_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer",
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#confidence in community institutions
res32_full_tab<- data.frame(Treat.Effect  = round(res32_full$beta, 2),
                            SE = sapply(round(res32_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res32_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer",
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#confidence that school will be sustained
res33_full_tab<- data.frame(Treat.Effect  = round(res33_full$beta, 2),
                            SE = sapply(round(res33_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res33_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer",
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#MOE provisions for funding teachers
res34_full_tab<- data.frame(Treat.Effect  = round(res34_full$beta, 2),
                            SE = sapply(round(res34_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res34_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer",
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Shura provisions for future classes
res35_full_tab<- data.frame(Treat.Effect  = round(res35_full$beta, 2),
                            SE = sapply(round(res35_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res35_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer",
                              "hhhead_age", "hhhead_schoolyears", "school_km")

tab_a13_cl_full<-multimerge( list (one=res30_full_tab, two=res31_full_tab, three=res32_full_tab,
                                   four=res33_full_tab, five=res34_full_tab, six=res35_full_tab))

tab_a13_cl_full_format_print<-xtable(tab_a13_cl_full,
                                               caption="\\label{tab:tab_a13_cl_full}Effects of Sustainability Model on Sustainability Outcomes for Community Leaders")

columns<-c("Combined Sustainability Index", "Community Provision for Future Classes", "Confidence in Community Instns.", 
           "Confidence that School Will be Sustained", "MOE Provisions for Funding Teachers", "Shura Provisions for Future Classes")
N<-c(length(lm30$residuals), length(lm31$residuals), length(lm32$residuals), 
     length(lm33$residuals), length(lm34$residuals), length(lm35$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a13_cl_full.tex")
print(tab_a13_cl_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#includes a little manual formatting

# one table for the teacher outcomes
#Combined sustainability index index
res36_full_tab<- data.frame(Coef. = round(res36_full$beta, 2),
                            SE = sapply(round(res36_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res36_full_tab) <- c("Intercept", "Treatment", "ts_cv")

#confidence in local community institutions
res37_full_tab<- data.frame(Coef.  = round(res37_full$beta, 2),
                            SE = sapply(round(res37_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res37_full_tab) <- c("Intercept", "Treatment", "ts_cv")

#Confidence that school will be sustained
res38_full_tab<- data.frame(Coef. = round(res38_full$beta, 2),
                            SE = sapply(round(res38_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res38_full_tab) <- c("Intercept", "Treatment", "ts_cv")

#proactive management from MOE
res39_full_tab<- data.frame(Coef. = round(res39_full$beta, 2),
                            SE = sapply(round(res39_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res39_full_tab) <- c("Intercept", "Treatment", "ts_cv")

#Proactive management from shuras
res40_full_tab<- data.frame(Coef. = round(res40_full$beta, 2),
                            SE = sapply(round(res40_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res40_full_tab) <- c("Intercept", "Treatment", "ts_cv")

#Teacher plans to remain CBE teacher
res41_full_tab<- data.frame(Coef.  = round(res41_full$beta, 2),
                            SE = sapply(round(res41_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res41_full_tab) <- c("Intercept", "Treatment", "ts_cv")

tab_a13_ts_full<-multimerge( list (one=res36_full_tab, two=res37_full_tab, three=res38_full_tab,
                                   four=res39_full_tab, five=res40_full_tab, six=res41_full_tab))

tab_a13_ts_full_format_print<-xtable(tab_a13_ts_full,
                                     caption="\\label{tab:tab_a13_ts_full}Effects of Sustainability Model on Sustainability Outcomes for Teachers")


columns<-c("Combined Sustainability Index", "Confidence in Local Community Instns.", "Confidence that School Will be Sustained", 
           "Proactive Management from MOE", "Proactive Management from Shuras", "Teacher plans to remain CBE Teacher")
N<-c(length(lm36$residuals), length(lm37$residuals), length(lm38$residuals), 
     length(lm39$residuals), length(lm40$residuals), length(lm41$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a13_ts_full.tex")
print(tab_a13_ts_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#includes a little manual formatting

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A14 IN MAIN APPENDIX
##########################################################

#  child outcomes and covariates
# attendance
res1.crs_full_tab<- data.frame(Coef. = round(res1.crs_full$beta, 2),
                            SE = sapply(round(res1.crs_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res1.crs_full_tab) <- c("Intercept", "Treatment", "CRS", "Treatment X CRS",
                                 "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", 
                                 "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                 "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", "hhhead_edu_mosque", "hhhead_edu_madrassa",
                                 "hhhead_edu_community", "hhhead_edu_government", "hhhead_edu_university", "hhhead_female", "hh_totalincome_2001less", 
                                 "hh_totalincome_2001to5000", "hhhead_totalincome_5001to10000", "hhhead_totalincome_10001to15000", "hh_totalincome_15001plus",
                                 "hh_own_tvs", "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children", "PROVINCE1", 
                                 "PROVINCE3", "PROVINCE4", "PROVINCE5")

# test scores
res2.crs_full_tab<- data.frame(Coef. = round(res2.crs_full$beta, 2),
                            SE = sapply(round(res2.crs_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res2.crs_full_tab) <- c("Intercept", "Treatment", "CRS", "Treatment X CRS",
                                 "ros_hhheadchild", "ros_girl", "ros_age", "int_lang_pashto", "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", 
                                 "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                 "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", "hhhead_edu_mosque", "hhhead_edu_madrassa",
                                 "hhhead_edu_community", "hhhead_edu_government", "hhhead_edu_university", "hhhead_female", "hh_totalincome_2001less", 
                                 "hh_totalincome_2001to5000", "hhhead_totalincome_5001to10000", "hhhead_totalincome_10001to15000", "hh_totalincome_15001plus",
                                 "hh_own_tvs", "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children", "PROVINCE1", 
                                 "PROVINCE3", "PROVINCE4", "PROVINCE5")


#  household satisfaction outcome and covariates

# test scores
res3.crs_full_tab<- data.frame(Coef. = round(res3.crs_full$beta, 2),
                               SE = sapply(round(res3.crs_full$SE, 2),
                                           function(x) {paste0("(",x,")")}))

rownames(res3.crs_full_tab) <- c("Intercept", "Treatment", "CRS", "Treatment X CRS",
                                 "int_lang_pashto", "hh_eth_hazara", "hh_eth_pashtun", "hh_eth_tajik", 
                                 "hhhead_job_farmer", "hhhead_age", "hhhead_schoolyears", "hh_num", "hh_jeribs", "hh_animal_sheep", "school_km", 
                                 "hhhead_job_laborer", "hhhead_job_military", "hhhead_write", "hhhead_read", "hhhead_edu_mosque", "hhhead_edu_madrassa",
                                 "hhhead_edu_community", "hhhead_edu_government", "hhhead_edu_university", "hhhead_female", "hh_totalincome_2001less", 
                                 "hh_totalincome_2001to5000", "hhhead_totalincome_5001to10000", "hhhead_totalincome_10001to15000", "hh_totalincome_15001plus",
                                 "hh_own_tvs", "hh_own_mobiles", "hh_own_cars", "hh_own_radios", "factorwealth", "hh_landown", "hh_children", "PROVINCE1", 
                                 "PROVINCE3", "PROVINCE4", "PROVINCE5")

tab_a14_full<-multimerge( list (one=res1.crs_full_tab, two=res2.crs_full_tab, three=res3.crs_full_tab))

tab_a14_full_format_print<-xtable(tab_a14_full,
                                               caption="\\label{tab:tab_a14_full}Heterogeneous Treatment Effects by Implementing NGO")


columns<-c("Child Attendance", "Child Test Score", "Household Satisfaction")
N<-c(length(lm1.crs$residuals), length(lm2.crs$residuals), length(lm3.crs$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a14_full.tex")
print(tab_a14_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#requires a little bit of manual formatting, added in het.p-value from main table

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A15 IN MAIN APPENDIX
##########################################################

#one table for the equivalency outcome

res42_full_tab<- data.frame(Coef.= round(res42_full$beta, 2),
                               SE = sapply(round(res42_full$SE, 2),
                                           function(x) {paste0("(",x,")")}))

rownames(res42_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer", 
                                 "hhhead_age", "hhhead_schoolyears", "school_km")

res42_full_tab_format_print<-xtable(res42_full_tab,
                                  caption="\\label{tab:tab_a15_full_equiv}Community Leaders' Longer-Term Perceptions of CBE Sustainability (CARE and CRS Samples) - Equivalency Outcome")

columns<-c("Community Desire to Continue CBE")
N<-c(length(lm42$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a15_full_equiv.tex")
print(res42_full_tab_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

#one table for the non-equivalency outcomes
# combined sustainability outcome
res43_full_tab<- data.frame(Coef. = round(res43_full$beta, 2),
                            SE = sapply(round(res43_full$SE, 2),
                                              function(x) {paste0("(",x,")")}))

rownames(res43_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Initiative to have CBE sustained
res44_full_tab<- data.frame(Coef. = round(res44_full$beta, 2),
                           SE = sapply(round(res44_full$SE, 2),
                                              function(x) {paste0("(",x,")")}))

rownames(res44_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Provisions for sustainability without NGO
res45_full_tab<- data.frame(Coef. = round(res45_full$beta, 2),
                            SE = sapply(round(res45_full$SE, 2),
                                              function(x) {paste0("(",x,")")}))

rownames(res45_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Confidence that school will sustain
res46_full_tab<- data.frame(Coef. = round(res46_full$beta, 2),
                            SE = sapply(round(res46_full$SE, 2),
                                              function(x) {paste0("(",x,")")}))

rownames(res46_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Continued CBE operations in spring 2018
res47_full_tab<- data.frame(Coef. = round(res47_full$beta, 2),
                            SE = sapply(round(res47_full$SE, 2),
                                              function(x) {paste0("(",x,")")}))

rownames(res47_full_tab) <- c("Intercept", "Treatment", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")


tab_a15_full_nonequiv<-multimerge( list (one=res43_full_tab, two=res44_full_tab, three=res45_full_tab, four=res46_full_tab, five=res47_full_tab))

tab_a15_full_nonequiv_format_print<-xtable(tab_a15_full_nonequiv,
                                  caption="\\label{tab:tab_a15_full_nonequiv}Community Leaders' Longer-Term Perceptions of CBE Sustainability (CARE and CRS Samples) - Non-Equivalency Outcomes")

columns<-c("Combined Sustainability Index", "Initiative to have CBE Sustained", "Provisions for Sustainability Without NGO",
           "Confidence that School Will Sustain", "Confinued CBE Operations in Spring 2018")
N<-c(length(lm44$residuals), length(lm44$residuals), length(lm45$residuals), length(lm46$residuals), length(lm47$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a15_full_nonequiv.tex")
print(tab_a15_full_nonequiv_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()
#need to do a little manul formatting

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A16 IN MAIN APPENDIX
##########################################################

#one table with the regressions for community leader's age 

#combined sustainability index
res48_full_tab<- data.frame(Coef.= round(res48_full$beta, 2),
                            SE = sapply(round(res48_full$SE, 2),
                                              function(x) {paste0("(",x,")")}))

rownames(res48_full_tab) <- c("Intercept", "Treatment", "Older leader", 
                              "Treatment x Older Leader", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Community provision for future classes
res48b_full_tab<- data.frame(Coef.= round(res48b_full$beta, 2),
                            SE = sapply(round(res48b_full$SE, 2),
                                              function(x) {paste0("(",x,")")}))

rownames(res48b_full_tab) <- c("Intercept", "Treatment", "Older leader", 
                              "Treatment x Older Leader", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Confidence in community institutions
res48c_full_tab<- data.frame(Coef.= round(res48c_full$beta, 2),
                             SE = sapply(round(res48c_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res48c_full_tab) <- c("Intercept", "Treatment", "Older leader", 
                               "Treatment x Older Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#Confidence that school will be sustained
res48d_full_tab<- data.frame(Coef.= round(res48d_full$beta, 2),
                             SE = sapply(round(res48d_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res48d_full_tab) <- c("Intercept", "Treatment", "Older leader", 
                               "Treatment x Older Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#MOE provisions for funding teachers
res48e_full_tab<- data.frame(Coef.= round(res48e_full$beta, 2),
                             SE = sapply(round(res48e_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res48e_full_tab) <- c("Intercept", "Treatment", "Older leader", 
                               "Treatment x Older Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#MOE provisions for funding teachers
res48f_full_tab<- data.frame(Coef.= round(res48f_full$beta, 2),
                             SE = sapply(round(res48f_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res48f_full_tab) <- c("Intercept", "Treatment", "Older leader", 
                               "Treatment x Older Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

tab_a16_full_age<-multimerge( list (one=res48_full_tab, two=res48b_full_tab, three=res48c_full_tab, 
                                    four=res48d_full_tab, five=res48e_full_tab, six=res48f_full_tab))

tab_a16_full_age_format_print<-xtable(tab_a16_full_age,
                                           caption="\\label{tab:tab_a16_full_age}Interaction Effect Regressions With Community Leaders' Age, Endline Community Leader Sustainability Perceptions")

columns<-c("Combined Sustainability Index", "Community Provisions for Future Classes", "Confidence in Community Instns.",
           "Confidence that School Will Be Sustained", "MOE provisions for Funding Teachers", "Shura Provisions for Future Classes")
N<-c(length(lm48$residuals), length(lm48b$residuals), length(lm48c$residuals), length(lm48d$residuals), length(lm48e$residuals), length(lm48f$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')


sink(file="tabs-figs/tab_a16_full_age.tex")
print(tab_a16_full_age_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

#one table with the regressions for community leader's education 

#combined sustainability index
res49_full_tab<- data.frame(Coef.= round(res49_full$beta, 2),
                            SE = sapply(round(res49_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res49_full_tab) <- c("Intercept", "Treatment", "Educated leader", 
                              "Treatment x Educated Leader", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Community provision for future classes
res49b_full_tab<- data.frame(Coef.= round(res49b_full$beta, 2),
                             SE = sapply(round(res49b_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res49b_full_tab) <- c("Intercept", "Treatment", "Educated leader", 
                               "Treatment x Educated Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#Confidence in community institutions
res49c_full_tab<- data.frame(Coef.= round(res49c_full$beta, 2),
                             SE = sapply(round(res49c_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res49c_full_tab) <- c("Intercept", "Treatment", "Educated leader", 
                               "Treatment x Educated Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#Confidence that school will be sustained
res49d_full_tab<- data.frame(Coef.= round(res49d_full$beta, 2),
                             SE = sapply(round(res49d_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res49d_full_tab) <- c("Intercept", "Treatment", "Educated leader", 
                               "Treatment x Educated Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#MOE provisions for funding teachers
res49e_full_tab<- data.frame(Coef.= round(res48e_full$beta, 2),
                             SE = sapply(round(res48e_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res49e_full_tab) <- c("Intercept", "Treatment", "Educated leader", 
                               "Treatment x Educated Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#MOE provisions for funding teachers
res49f_full_tab<- data.frame(Coef.= round(res49f_full$beta, 2),
                             SE = sapply(round(res49f_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res49f_full_tab) <- c("Intercept", "Treatment", "Educated leader", 
                               "Treatment x Educated Leader", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

tab_a16_full_educ<-multimerge( list (one=res49_full_tab, two=res49b_full_tab, three=res49c_full_tab, 
                                    four=res49d_full_tab, five=res49e_full_tab, six=res49f_full_tab))

tab_a16_full_educ_format_print<-xtable(tab_a16_full_educ,
                                      caption="\\label{tab:tab_a16_full_educ}Interaction Effect Regressions With Community Leaders' Educational Status, Endline Community Leader Sustainability Perceptions")

columns<-c("Combined Sustainability Index", "Community Provisions for Future Classes", "Confidence in Community Instns.",
           "Confidence that School Will Be Sustained", "MOE provisions for Funding Teachers", "Shura Provisions for Future Classes")
N<-c(length(lm49$residuals), length(lm49b$residuals), length(lm49c$residuals), length(lm49d$residuals), length(lm49e$residuals), length(lm49f$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')


sink(file="tabs-figs/tab_a16_full_educ.tex")
print(tab_a16_full_educ_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

##########################################################
#### FULL COVARIATE OUTPUT FOR TABLE A17 IN MAIN APPENDIX
##########################################################

#combined sustainability index
res106_full_tab<- data.frame(Coef.= round(res106_full$beta, 2),
                            SE = sapply(round(res106_full$SE, 2),
                                        function(x) {paste0("(",x,")")}))

rownames(res106_full_tab) <- c("Intercept", "Treatment", "Mean Test Score", 
                              "Treatment x Mean Test Score", "int_lang_pashto", "hhhead_job_farmer", 
                              "hhhead_age", "hhhead_schoolyears", "school_km")

#Community provision for future classes
res101_full_tab<- data.frame(Coef.= round(res101_full$beta, 2),
                             SE = sapply(round(res101_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res101_full_tab) <- c("Intercept", "Treatment", "Mean Test Score", 
                               "Treatment x Mean Test Score", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#Confidence in community institutions
res102_full_tab<- data.frame(Coef.= round(res102_full$beta, 2),
                             SE = sapply(round(res102_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res102_full_tab) <- c("Intercept", "Treatment", "Mean Test Score", 
                               "Treatment x Mean Test Score", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#Confidence that school will be sustained
res103_full_tab<- data.frame(Coef.= round(res103_full$beta, 2),
                             SE = sapply(round(res103_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res103_full_tab) <- c("Intercept", "Treatment", "Mean Test Score", 
                               "Treatment x Mean Test Score", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#MOE provisions for funding teachers
res104_full_tab<- data.frame(Coef.= round(res104_full$beta, 2),
                             SE = sapply(round(res104_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res104_full_tab) <- c("Intercept", "Treatment", "Mean Test Score", 
                               "Treatment x Mean Test Score", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

#Shura provisions for future classes
res105_full_tab<- data.frame(Coef.= round(res105_full$beta, 2),
                             SE = sapply(round(res105_full$SE, 2),
                                         function(x) {paste0("(",x,")")}))

rownames(res105_full_tab) <- c("Intercept", "Treatment", "Mean Test Score", 
                               "Treatment x Mean Test Score", "int_lang_pashto", "hhhead_job_farmer", 
                               "hhhead_age", "hhhead_schoolyears", "school_km")

tab_a17_full<-multimerge( list (one=res106_full_tab, two=res101_full_tab, three=res102_full_tab, 
                                     four=res103_full_tab, five=res104_full_tab, six=res105_full_tab))

tab_a17_full_format_print<-xtable(tab_a17_full,
                                       caption="\\label{tab:tab_a17_full}Interaction Effect Regressions With Community Mean Children's Test Score, Endline Community Leader Sustainability Perceptions")

columns<-c("Combined Sustainability Index", "Community Provisions for Future Classes", "Confidence in Community Instns.",
           "Confidence that School Will Be Sustained", "MOE provisions for Funding Teachers", "Shura Provisions for Future Classes")
N<-c(length(lm106$residuals), length(lm101$residuals), length(lm102$residuals), length(lm103$residuals), length(lm104$residuals), length(lm105$residuals))
addtorow<- list()
addtorow$pos <-list(0)
addtorow$command <-paste0(paste0('& \\multicolumn{2}{c}{', unique(columns), '}', collapse=''), '\\\\',
                          paste0('&\\multicolumn{2}{c}{', N, '}', collapse=''), '\\\\')

sink(file="tabs-figs/tab_a17_full.tex")
print(tab_a17_full_format_print, 
      caption.placement = "top",
      add.to.row=addtorow,
      hline.after = -1)
sink()

#############################################################################################
### TABLE A22: EFFECT OF TREATMENT ON PARENTAL INVOLVEMENT
############################################################################################
## Household outcome 1: parental involvement in student's homework

y.p1 <- within_hh_dat$q37_recode
lmp1<-lm( formula(paste("y.p1", "XX_hh", sep="~")),  weights=within_hh_dat$wt)
resp1<-coef_test(lmp1, vcov=vcovCR(lmp1, cluster=within_hh_dat$CLUSTER, type="CR2"))
print(resp1)

#full results with all covariates [for appendix]
resp1full<-as.data.frame(resp1)

#main results without all the covariates [for main body of paper]
resp1<-as.data.frame(resp1[2,]) # keep second row of output 

# add in columns on the sesoi for teacher_attend_score
sesoip1<- sesoi_gen
zp1<-(resp1[,"beta"]-sesoip1)/resp1[,"SE"]
p_sesoip1=pt(-zp1, df = resp1[,"df_Satt"])

# add in t_Satt_citical
tp1 <-sapply(resp1$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for parental involvement in homework
resp1<-cbind(resp1, sesoi=sesoip1, p_sesoi=p_sesoip1, t_Satt_crit=tp1, ci_l=resp1$beta-tp1*resp1[,"SE"],
             ci_u=resp1[,"beta"]+tp1*resp1[,"SE"],
             coverage=0.9, N=length(lmp1$residuals))
rownames(resp1)<-paste(rownames(resp1), 'parent_involv_hw')
resp1

# Household outcome 2: parental contributions

y.p2<-within_hh_dat$q40
lmp2<-lm( formula(paste("y.p2", "XX_hh", sep="~")),  weights=within_hh_dat$wt)
resp2<-coef_test(lmp2, vcov=vcovCR(lmp2, cluster=within_hh_dat$CLUSTER, type="CR2"))
print(resp2)

#full results with all covariates [for appendix]
resp2full<-as.data.frame(resp2)

#main results without all the covariates [for main body of paper]
resp2<-as.data.frame(resp2[2,]) # keep second row of output 

# add in columns on the sesoi for parent_contribution
sesoip2<- sesoi_gen
zp2<-(resp2[,"beta"]-sesoip2)/resp2[,"SE"]
p_sesoip2=pt(-zp2, df = resp2[,"df_Satt"])

# add in t_Satt_citical
tp2 <-sapply(resp2$df, function(d) qt(1-(1-0.9)/2, df=d)) # ci= 0.9

# final set of results for parent_contribution
resp2<-cbind(resp2, sesoi=sesoip2, p_sesoi=p_sesoip2, t_Satt_crit=tp2, ci_l=resp2$beta-tp2*resp2[,"SE"],
             ci_u=resp2[,"beta"]+tp2*resp2[,"SE"],
             coverage=0.9, N=length(lmp2$residuals))
rownames(resp2)<-paste(rownames(resp2), 'parental_contributions')
resp2

# combining results in Table together

statp1<-jmsummary(within_hh_dat$q37_recode)
rownames(statp1) <- "Parental involvement in homework"

statp2<-jmsummary(within_hh_dat$q40)
rownames(statp2) <- "Parental contributions"

TableX_Output<-rbind(resp1, resp2)
TableX_sum <- rbind(statp1, statp2)
TableX_format <- data.frame(Treatment.Effect = round(TableX_Output$beta, 2),
                            Std.Err. = sapply(round(TableX_Output$SE, 2),
                                              function(x) {paste0("(",x,")")}),
                            N = TableX_Output$N,
                            Control.Mean = round(TableX_sum[,"mean"],2),
                            Control.Std.Dev. = round(TableX_sum[,"sd"],2))
rownames(TableX_format) <- rownames(TableX_sum)

TableX_print<-xtable(TableX_format,
                     caption="\\label{tab:parents_involv}Parent's Involvement and Contributions")

addtorow <- list()
addtorow$pos <- list(0,1,1)
addtorow$command <- c("{\  &  &  &  & &  & &\\\\\n",
                      "\\\\\n",
                      "{\  &  &  &  & &  & & \\\\\n")
sink(file="tabs-figs/hh_parent_involvment.tex")
print(TableX_print, 
      add.to.row = addtorow,
      caption.placement = "top",
      hline.after = -1)
sink()

table(within_hh_dat$q40)

